C++求数组是否含有重复元素
PHPz
PHPz 2017-04-17 14:26:02
0
1
550
PHPz
PHPz

学习是最好的投资!

reply all(1)
黄舟
#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. . .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template