I use set instead of map!


  • 6
    P
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_set<int> hashSet;
        if (!k) return false;
        if (k >= nums.size()) k = nums.size()-1;
        for (int i = 0;i <= k;++i)
            if (hashSet.find(nums[i]) == hashSet.end())
                hashSet.insert(nums[i]);
            else
                return true;
        for (int i = k+1;i < nums.size();++i) {
            hashSet.erase(nums[i-k-1]);
            if (hashSet.find(nums[i]) == hashSet.end())
                hashSet.insert(nums[i]);
            else
                return true;
        }
        return false;
    }

Log in to reply
 

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