C++ very simple solution using map


  • 0
    T
    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            std::unordered_map<int, int> hmap;
            
            for (int i = 0; i < nums.size(); i++) {
                if (hmap.find(nums[i]) != hmap.end() && (i - hmap.find(nums[i])->second <= k))
                    return true;
                hmap[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.