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 i and j is at most k.
此题在上一题Contains Duplicate的基础上,要求重复元素的半径不大于K。上题中,map中元素值为Key,元素索引下表为Value。所以在找到重复的情况下,可以判断下标差是否小于等于K。如果大于K,则修改已在map中元素对应的value,即下标。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int, int>int_map;
map<int,int>::iterator iter;
for (int i = 0; i<nums.size(); i++) {
if((iter=int_map.find(nums[i]) )!= int_map.end() ){
if (i - iter->second <= k) {
return true;
}else{
int_map.erase(iter);
}
}
int_map.insert(pair<int, int>(nums[i], i));
}
return false;
}
};