-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdupbyslidingwindow.cpp
More file actions
54 lines (43 loc) · 1.29 KB
/
dupbyslidingwindow.cpp
File metadata and controls
54 lines (43 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int n = nums.size();
if (k == 0) return false; // No valid window
// Sliding window as an array (instead of set)
vector<int> window;
for (int i = 0; i < n; i++) {
// Check if the number already exists in window
for (int j = 0; j < window.size(); j++) {
if (window[j] == nums[i]) {
return true;
}
}
// Add current number to the window
window.push_back(nums[i]);
// Maintain the window size ≤ k
if (window.size() > k) {
// Remove the oldest element (front)
for (int j = 0; j < window.size() - 1; j++) {
window[j] = window[j + 1];
}
window.pop_back(); // Remove last element
}
}
return false;
}
};
int main() {
int n, k;
cin >> n;
vector<int> nums(n);
for (int i = 0; i < n; i++) {
cin >> nums[i];
}
cin >> k;
Solution obj;
cout << (obj.containsNearbyDuplicate(nums, k) ? "true" : "false") << endl;
return 0;
}