题目:
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 j is at most k.
解答:
直接维护一个大小为k的窗口即可,可以用map<int,bool>记录在此窗口中是否出现某个数字,然后判断是否有重复
看到一个直接用hash的也能过的代码,然而其实是有bug的,说明leetcode的测试数据还是很弱的,下面附上
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int len=nums.size();
int *hashTable=new int[sizeof(int)*len];
for(int i=0;i<len;++i){
hashTable[i]=-99999999;
}
for(int i=0;i<len;++i){
int hash=nums[i]%len;
if(i-hashTable[hash]<=k){
return true;
} else {
hashTable[hash]=i;
}
}
return false;
}
};