-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathContainsDuplicatesII219.java
76 lines (63 loc) · 1.97 KB
/
ContainsDuplicatesII219.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
69
70
71
72
73
74
75
76
/**
* Given an array of integers and an integer k, find out whether there are
* two distinct indices i and j in the array such that nums[i] = nums[j] and
* the absolute difference between i and j is at most k.
*/
import java.util.HashSet;
import java.util.Set;
import java.util.HashMap;
import java.util.Map;
public class ContainsDuplicatesII219 {
// too slow
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (nums.length < 2) {
return false;
}
for (int i = 0; i < nums.length; i++) {
int numI = nums[i];
for (int j = i + 1; j < nums.length && j - i <= k; j++) {
int numJ = nums[j];
if (numI == numJ) {
return true;
}
}
}
return false;
}
public boolean containsNearbyDuplicate2(int[] nums, int k) {
if (nums.length < 2) {
return false;
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer key = nums[i];
if (map.containsKey(key)) {
if (i - map.get(key) <= k) {
return true;
}
}
map.put(key, i);
}
return false;
}
/**
* https://discuss.leetcode.com/topic/15305/simple-java-solution
*/
public boolean containsNearbyDuplicate3(int[] nums, int k) {
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < nums.length; i++) {
if(i > k) {
set.remove(nums[i-k-1]);
}
if(!set.add(nums[i])) {
return true;
}
}
return false;
}
public static void main(String[] args) {
ContainsDuplicatesII219 cd2 = new ContainsDuplicatesII219();
System.out.println(cd2.containsNearbyDuplicate2(new int[]{5, 8, 2, 10, 5}, 4));
System.out.println(cd2.containsNearbyDuplicate2(new int[]{5, 8, 2, 10}, 1));
}
}