219. Contains Duplicate II

# Easy

Key idea: only two elements in the list are the same. Then this problem is easy. unordered_map

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, int> m;
        for(int i = 0; i < nums.size(); i ++) {
            if(m.find(nums[i]) != m.end() && i-m[nums[i]] <= k)
                return true;
            m[nums[i]] = i;
        }
        return false;
    }
};

Last updated