Contains Duplicate II
Given an array of integers and an integer k, return true if and only if 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.
解题思路:
可以用一个set记录滑动窗口大小的所有元素,随着滑动窗口往右移,左边的陆续删除,添加右边的。若set中出现相同元素,那么返回true。否则返回false。注意题意中的k是指j-i=k。
class Solution {
public:
bool containsNearbyDuplicate(vector& nums, int k) {
int len = nums.size();
if(k <= 0 || len<=0){
return false;
}
set s;
for(int i = 0; ik){
s.erase(nums[i - k - 1]);
}
if(s.find(nums[i])!=s.end()){
return true;
}
s.insert(nums[i]);
}
return false;
}
};
原文作者:;如有侵权,请联系管理员删除。