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.
Subscribe to see which companies asked this question
类似217。
注:做了这么久,才发现有速度的评比,以后重做时。会注意优化
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int, int> temp;
for(int i = 0; i < nums.size(); ++i)
{
/* if(temp.find(nums[i]) == temp.end())
temp[nums[i]] = i;
else
{ if(i - temp[nums[i]] <= k)
return true;
else
temp[nums[i]] = i;
}*/
if(temp.find(nums[i]) != temp.end() && i - temp[nums[i]] <= k)
return true;
else
temp[nums[i]] = i;
}
return false;
}
};