Very simple C++ solution (36ms)

  • 3
    bool containsDuplicate(vector<int>& nums) {
        // empty array or single element has no duplicate
        if( (nums.size() == 0) || (nums.size() == 1) ) return false;
        // sort array
        std::sort(std::begin(nums), std::end(nums));
        // search for duplicate
        for(int i = 0; i < nums.size()-1; i++)
           if(nums[i] == nums[i+1]) return true;
        return false;

  • 0

    There is a bug, should be i < nums.size() - 1

  • 0

    Actually, if you want to compare i < nums.size()-1 you should use i < int(nums.size()-1)

  • 0

    The original program should work on most platforms as the capacity of a vector is usually much larger than its actual size so the element after the last can be indexed.
    But I changed to nums.size() - 1 just to be safe

  • 0

    It's a very good solution, but I believe std::sort is O(nlogn) in average, which is a little bit slow than hashtable.

  • 1

    I believe you are right. But why the runtime is shorter with std::sort?

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.