File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments