C++ simple using map


  • 0
    X
    class Solution {
    public:
        // it's like histogram
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            if(nums.empty() || k <= 0){
                return false;
            }
            int size = nums.size();
            unordered_map<int, int> m;
            int i = 0;
            while(i < k + 1 && i < size){
                if(m.find(nums[i]) == m.end()){
                    m[nums[i]] = 1;
                }else{
                    return true;
                }
                ++i;
            }
            for(; i < size; ++i){
                if(m[nums[i - k - 1]] <= 1){
                    m.erase(nums[i - k - 1]);
                }else{
                    --m[nums[i - k - 1]];
                }
                if(m.find(nums[i]) == m.end()){
                    m[nums[i]] = 1;
                }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.