【LeetCode】219. Contains Duplicate II

Contains Duplicate II

Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.

 

使用unordered_map记录每个值与对应index位置,当出现重复值时,比较index距离是否在k之内,

注意index的更新

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

你可能感兴趣的:(LeetCode)