Unordered_map based C++ solution, beats 98% of other runs


  • 0
    B
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            if (nums.empty() || k==0) return false;
            unordered_map<int,int> mymap;  //num, index
            for (int i=1; i < nums.size()+1; i++)   //we increment i, since the default for a key is zero
              {
              int x = nums[i-1];
              if (mymap[x])
                {
                    if (i-mymap[x] <= k) 
                      return true;
                    else 
                      mymap[x] = i;
                }
              else
                mymap[x]=i;
              }
             return false;
        }

Log in to reply
 

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