/**
* @brief 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 absolute difference between i and j is at most k.
*
* example1:
* input :nums[1,2,3,1],k=3
* Output:true
*
* example2:
* input:nums[1,0,1,1],k=1
* output:true
*
* example3:
* Input:nums[1,2,3,1,2,3],k=2
* output:false
*/
class Solution{
public:
bool containsNearbyDuplicate(vector<int>& nums, int k){
unordered_map<int,int> m;
for(int i = 0; i < nums.size(); i++){
int n = nums[i];
if(m.find(n) != m.end() && i - m[n] <=k){
return true;
}
m[n] = i;
}
return false;
}
};
怕什么真理无穷,进一寸有一寸的欢喜。---胡适
浙公网安备 33010602011771号