Easy Understanding C++ Solution @99.23%


  • 0
    B

    Updated codes using unordered_map, which can deal with negative integers:

    class Solution {
    public:
        bool containsDuplicate(vector<int>& nums) {
            unordered_map<int,int> hs;
            int n = nums.size();
            for(int i = 0; i < n; i++){
                if(hs[nums[i]] == 0)
                    hs[nums[i]]++;
                else if(hs[nums[i]] == 1)//If flag[key] = 1, then key already exists.
                    return true;
            }
        return false;
        }
    };
    

    Following are the former code, which can only deal with positive numbers:

    • If flag[key] = 1, then key already exists.
    class Solution {
    public:
            bool containsDuplicate(vector<int>& nums) {
            int flag[1000000] = {0};
            int n = nums.size();
            for(int i = 0; i < n; i++){
                if(flag[nums[i]] == 0)
                    flag[nums[i]]++;
                else if(flag[nums[i]] == 1)
                    return true;
            }
        return false;
        }
    };
    

  • 0
    K

    i am sorry, you are wrong, consider if the array contains negative number, your solution won't work


  • 0
    B
    This post is deleted!

  • 0
    B

    @kangpei

    Thank you! You are right.

    If the test case contains negative integers, we can use Unordered_map to save the frequency. And I have updated the answer.

    Actually, problem 219 has negative integers in its test cases.


  • 0
    A
      return unordered_set<int>(nums.cbegin(), nums.cend()).size() != nums.size();
    

Log in to reply
 

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