forked from yubinbai/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
37 lines (33 loc) · 1.04 KB
/
Solution.java
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
import java.util.*;
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashSet<Integer> set = new HashSet<Integer>();
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
for (int i : nums) {
if (set.contains(i)) return true;
if (q.size() == k && k != 0) {
int old = q.pollFirst();
set.remove(old);
}
if (k != 0) {
set.add(i);
q.add(i);
}
}
return false;
}
public static void main(String[] args) {
Solution s = new Solution();
int[] nums;
int k;
nums = new int[] {1, 2, 3, 1};
k = 2;
System.out.println(s.containsNearbyDuplicate(nums, k));
nums = new int[] {1, 2, 3, 1, 4, 5};
k = 3;
System.out.println(s.containsNearbyDuplicate(nums, k));
nums = new int[] {1, 2, 3, 1, 4, 5};
k = 0;
System.out.println(s.containsNearbyDuplicate(nums, k));
}
}