描述
Given an array
of integers and an integer k
, find out whether there are two distinct indices i
and j
in the array such that nums[i] = nums[j]
and the absolute difference between i
and j
is at most k
.
樣例
Given nums = [1,2,1]
, k = 0
, return false
.
無難度題
class Solution {
public:
/**
* @param nums: the given array
* @param k: the given number
* @return: whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k
*/
bool containsNearbyDuplicate(vector<int> &nums, int k) {
// Write your code here
unordered_map<int,int> mmap;
for(int i=0;i<nums.size();i++){
if(mmap.find(nums[i])!=mmap.end()&&i-mmap[nums[i]]<=k) return true;
mmap[nums[i]]=i;
}
return false;
}
};