Easy to understand C++ solution 26ms


  • 0
    9
    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) 
        {
            if(nums.size() <= 1)
                return false;
            
            int n = nums.size();
            unordered_map<int,int> mymap;
            for(int i = 0; i < n; i++)
            {
                auto it = mymap.find(nums[i]);
                if(it != mymap.end())
                {
                    if(it->first == nums[i] && abs(it->second-i) <= k)
                        return true;
                    else
                    {
                        mymap.erase(it);
                        mymap[nums[i]] = i;
                    }
                }
                
                else
                    mymap[nums[i]] = i;
            }
            
            return false;
        }
    };
    

Log in to reply
 

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