search

Home  >  Q&A  >  body text

C++求数组是否含有重复元素

PHPzPHPz2885 days ago566

reply all(1)I'll reply

  • 黄舟

    黄舟2017-04-17 14:28:02

    #include <algorithm>
    #include <iostream>
    #include <vector>
    using namespace std;
    
    bool containsDuplicate(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        cout << nums.size() << endl;
        int j = 0;
        cout << nums.size() - 1 << endl;
        cout << ( j < nums.size() - 1) << endl;
        for (int i = 0; i < nums.size() - 1; i++) {
            cout << nums.size() << endl;
            if (nums[i] == nums[i + 1]) 
                return true;
        }
        return false;
    }
    
    int main() {
        vector<int> a;
        cout << containsDuplicate(a) << endl;
        return 0;
    }
    
    

    When nums.size() = 0, because the type of nums.size() is size_t, which is the typedef of unsigned long long, it can only be a positive number, so when nums.size() -1, nums.size() is 0, the answer is expressed in binary, is 2^64 - 1, a huge positive number, so WA. It is recommended not to write nums.size() inside for, as nums.size() will be called every time, which increases overhead. . .

    reply
    0
  • Cancelreply