-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContainsDuplicate2.java
More file actions
73 lines (52 loc) · 1.94 KB
/
ContainsDuplicate2.java
File metadata and controls
73 lines (52 loc) · 1.94 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package Algorithms.Hashing;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author Srinivas Vadige, srinivas.vadige@gmail.com
* @since 19 Sept 2025
* @link 219. Contains Duplicate II <a href="https://leetcode.com/problems/contains-duplicate-ii/">Leetcode link</a>
* @topics Array, Hash Table, Sliding Window
*/
public class ContainsDuplicate2 {
public static void main(String[] args) {
int[] nums = {1, 2, 3, 1};
int k = 3;
System.out.printf("containsNearbyDuplicate(nums) = %b\n", containsNearbyDuplicate(nums, k));
System.out.printf("containsNearbyDuplicate2(nums) = %b\n", containsNearbyDuplicate2(nums, k));
System.out.printf("containsNearbyDuplicate3(nums) = %b\n", containsNearbyDuplicate3(nums, k));
}
public static boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> seen = new HashSet<>();
for(int l=0, r=0; r<nums.length; r++) {
if (r-l > k) {
seen.remove(nums[l]);
l++;
}
if (!seen.add(nums[r])) {
return true;
}
}
return false;
}
public static boolean containsNearbyDuplicate2(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for(int i=0; i<nums.length; i++) {
int num = nums[i];
if(map.containsKey(num) && i - map.get(num) <= k) return true;
// if (Math.abs(i - map.getOrDefault(num, i+1+k)) <= k) return true;
map.put(num, i);
}
return false;
}
public static boolean containsNearbyDuplicate3(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for(int i=nums.length-1; i>=0; i--) {
int num = nums[i];
if (map.getOrDefault(num, i+1+k) - i <= k) return true;
map.put(num, i);
}
return false;
}
}