Problem Description:
Given an integer array and an integer K , if there are two different indexes in the array is determined i and j , such that the nums [i] = the nums [j] , and i and j maximum absolute value of the difference K .
Example 1:
Input: the nums = [1,2,3,1], K =. 3 Output: to true
Example 2:
Input: the nums = [1,0,1,1], K = . 1 Output: to true
Example 3:
Input: the nums = [1,2,3,1,2,3], K = 2 Output: to false
The basic idea:
Using the idea sliding window + hash set.
In the case of beginning the sliding window does not completely established, a special determination.
In the case of completion has been established, continue to delete and insert elements. To see if there are duplicate.
AC Code:
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int i = 0, j = 0;
set<int> s;
while (j != nums.size()) {
if (s.size() != k + 1) { // 处理刚开始的情况
if (s.count(nums[j])) { // 刚开始就有重复元素的情况
return true;
} else {
s.insert(nums[j++]);
}
} else { // 滑动窗口已经建立的情况下
s.erase(nums[i++]);
if (s.count(nums[j])) {
return true;
} else {
s.insert(nums[j++]);
}
}
}
return false;
}
};