-
Notifications
You must be signed in to change notification settings - Fork 16
/
ContainsDuplicateII.java
68 lines (65 loc) · 2.27 KB
/
ContainsDuplicateII.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ContainsDuplicateII {
public static void main(String[] args) {
System.out.println(containsNearbyDuplicate(new int[] {1, 2, 3, 1, 2, 3}, 2));
}
// private static class Frequency {
// private static final Map<Integer, Integer> frequency = new HashMap<>();
//
// public static Frequency withWindowSize(int[] array, int window) {
// Frequency frequency = new Frequency();
// for (int index = 0 ; index < window ; index++) {
// frequency.add(array[index]);
// }
// return frequency;
// }
//
// public void add(int element) {
// frequency.put(element, frequency.getOrDefault(element, 0) + 1);
// }
//
// public void remove(int element) {
// if (contains(element)) {
// frequency.put(element, frequency.get(element) - 1);
// }
// }
//
// public boolean contains(int element) {
// return frequency.getOrDefault(element, 0) > 0;
// }
// }
//
// public static boolean containsNearbyDuplicate(int[] array, int k) {
// Frequency slidingWindow = Frequency.withWindowSize(array, k);
// for (int index = k ; index < array.length ; index++) {
// if (slidingWindow.contains(array[index])) {
// return true;
// }
// slidingWindow.add(array[index]);
// slidingWindow.remove(array[index - k]);
// }
// return false;
// }
public static boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> checkForDuplicatesSet = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
int preSize = checkForDuplicatesSet.size();
int currentNum = nums[i];
checkForDuplicatesSet.add(currentNum);
if (checkForDuplicatesSet.size() == preSize) {
int dupK = k, reverse = i - 1;
while ( dupK > 0) {
if ( nums[reverse] == currentNum) {
return true;
}
dupK--;
reverse--;
}
}
}
return false;
}
}