题目
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 difference between i and jis at most k
分析
.记录每个元素的第一次出现位置,当它第二次出现时判断与第一次出现位置距离是否小于等于k,若不符合,则用第二次出现位置替换第一次出现位置继续进行比较。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int,int> map;
for(int i = 0; i < nums.size(); i++)
{
if(map.count(nums[i]) && (i - map[nums[i]] <= k))
return true;
map[nums[i]] = i;
}
return false;
}
};