O(n) solution with unordered_map C++


  • -1
    O
    class Solution {
    public:
        bool containsDuplicate(vector<int>& nums) 
        {
            unordered_map<int, unsigned int> mp;
            for (auto& x: nums)
                mp[x]++;
            for (auto it = mp.begin(); it != mp.end(); ++it)
                {
                    if (it->second > 1)
                        return true;
                }
            return false;
        }
    };

  • 0
    A
        unordered_map<int, int> mymap;
        for(int i = 0; i < nums.size(); ++i) {
            mymap[nums[i]]++;
            
            if (mymap[nums[i]] > 1) {
                return true;
            }
        }
        return false;
    

    I guess this way you don't have to loop through again


  • 0
    O

    yep, you are right


Log in to reply
 

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