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.
题目意思是:在一个数组里找到两个相同的数,并且他们的索引值之差不超过k,那么返回true。
可以建立一个map映射,存放不重复的数值和对应的索引。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int, int> dup;
for(int i = 0; i < nums.size(); i++)
{
if(dup.find(nums[i]) != dup.end() && i - dup[nums[i]] <= k)
{
return true;
}
else
{
dup[nums[i]] = i;
}
}
return false;
}
};