Skip to content

Commit 0bade9e

Browse files
solves contains duplicates ii
1 parent 2305211 commit 0bade9e

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

Diff for: src/ContainsDuplicateII.java

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import java.util.HashMap;
2+
import java.util.HashSet;
3+
import java.util.Map;
4+
import java.util.Set;
5+
6+
public class ContainsDuplicateII {
7+
public static void main(String[] args) {
8+
System.out.println(containsNearbyDuplicate(new int[] {1, 2, 3, 1, 2, 3}, 2));
9+
}
10+
11+
// private static class Frequency {
12+
// private static final Map<Integer, Integer> frequency = new HashMap<>();
13+
//
14+
// public static Frequency withWindowSize(int[] array, int window) {
15+
// Frequency frequency = new Frequency();
16+
// for (int index = 0 ; index < window ; index++) {
17+
// frequency.add(array[index]);
18+
// }
19+
// return frequency;
20+
// }
21+
//
22+
// public void add(int element) {
23+
// frequency.put(element, frequency.getOrDefault(element, 0) + 1);
24+
// }
25+
//
26+
// public void remove(int element) {
27+
// if (contains(element)) {
28+
// frequency.put(element, frequency.get(element) - 1);
29+
// }
30+
// }
31+
//
32+
// public boolean contains(int element) {
33+
// return frequency.getOrDefault(element, 0) > 0;
34+
// }
35+
// }
36+
//
37+
// public static boolean containsNearbyDuplicate(int[] array, int k) {
38+
// Frequency slidingWindow = Frequency.withWindowSize(array, k);
39+
// for (int index = k ; index < array.length ; index++) {
40+
// if (slidingWindow.contains(array[index])) {
41+
// return true;
42+
// }
43+
// slidingWindow.add(array[index]);
44+
// slidingWindow.remove(array[index - k]);
45+
// }
46+
// return false;
47+
// }
48+
49+
public static boolean containsNearbyDuplicate(int[] nums, int k) {
50+
Set<Integer> checkForDuplicatesSet = new HashSet<>();
51+
for (int i = 0; i < nums.length; i++) {
52+
int preSize = checkForDuplicatesSet.size();
53+
int currentNum = nums[i];
54+
checkForDuplicatesSet.add(currentNum);
55+
if (checkForDuplicatesSet.size() == preSize) {
56+
int dupK = k, reverse = i - 1;
57+
while ( dupK > 0) {
58+
if ( nums[reverse] == currentNum) {
59+
return true;
60+
}
61+
dupK--;
62+
reverse--;
63+
}
64+
}
65+
}
66+
return false;
67+
}
68+
}

0 commit comments

Comments
 (0)