Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d2b7ae6

Browse files
committed
2017/3/31
1 parent 6d06837 commit d2b7ae6

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

No219_ContainsDuplicateII.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Given an array of integers and an integer k, find out whether there are
2+
// two distinct indices i and j in the array such that nums[i] = nums[j] and
3+
// the absolute difference between i and j is at most k.
4+
5+
6+
// class Solution {
7+
// public:
8+
// // This method will TLE
9+
// bool containsNearbyDuplicate(vector<int>& nums, int k) {
10+
// int n = nums.size();
11+
// for(int i = 0; i<n; i++){
12+
// for(int j=i+1; j<=i+k && j < n; j++){
13+
// if(nums[i] == nums[j]){
14+
// return true;
15+
// break;
16+
// }
17+
// }
18+
// }
19+
// return false;
20+
// }
21+
// };
22+
23+
24+
class Solution {
25+
public:
26+
// Sliding windows
27+
bool containsNearbyDuplicate(vector<int>& nums, int k) {
28+
unordered_set<int> hashSet;
29+
for(int i=0; i<nums.size(); i++){
30+
if(i > k){
31+
hashSet.erase(nums[i-k-1]);
32+
}
33+
34+
// Take care! here not judge if i>k, it operates everytime
35+
if(!hashSet.insert(nums[i]).second){
36+
return true;
37+
}
38+
}
39+
return false;
40+
}
41+
};
42+

0 commit comments

Comments
 (0)