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时 返回true,
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int size=nums.size();
if(size<=1||k<=0)
return false;
unordered_map<int,int> table;
for(int i=0;i<size;++i){
auto it=table.find(nums[i]);
if(it==table.end())
table[nums[i]]=i;
else{
if(i-table[nums[i]]<=k)
return true;
it->second=i;
}
}
return false;
}原文地址:http://searchcoding.blog.51cto.com/1335412/1751329