C++ solution 32ms.


  • 0
    L

    class Solution {

    public:

    bool containsNearbyDuplicate(vector<int>& nums, int k) {
    
        if (nums.size() == 0) {
            return false;
        }
        
        unordered_map<int, int> nums_map;
        
        for (int i = 0; i<nums.size(); i++) {
            
            unordered_map<int,int>::const_iterator got
                = nums_map.find(nums[i]);
    
            if (got == nums_map.end()) {
                nums_map[nums[i]] = i;
            } else {
                if (i - nums_map[nums[i]] <= k) {
                    return true;
                } else {
                    nums_map[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.