Skip to content

Commit bb6bf1d

Browse files
refactor 219
1 parent 1eb1230 commit bb6bf1d

File tree

2 files changed

+65
-4
lines changed

2 files changed

+65
-4
lines changed

src/main/java/com/fishercoder/solutions/_219.java

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,27 @@
11
package com.fishercoder.solutions;
22

33
import java.util.HashMap;
4+
import java.util.HashSet;
45
import java.util.Map;
6+
import java.util.Set;
57

6-
/**219. Contains Duplicate II
7-
8+
/**
9+
* 219. Contains Duplicate II
810
Given an array of integers and an integer k,
9-
find out whether there are two distinct indices i and j in
10-
the array such that nums[i] = nums[j] and the difference between i and j is at most k.
11+
find out whether there are two distinct indices i and j in the array
12+
such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
13+
14+
Example 1:
15+
Input: nums = [1,2,3,1], k = 3
16+
Output: true
17+
18+
Example 2:
19+
Input: nums = [1,0,1,1], k = 1
20+
Output: true
21+
22+
Example 3:
23+
Input: nums = [1,2,3,1,2,3], k = 2
24+
Output: false
1125
*/
1226
public class _219 {
1327

@@ -28,4 +42,19 @@ public boolean containsNearbyDuplicate(int[] nums, int k) {
2842
return false;
2943
}
3044
}
45+
46+
public static class Solution2 {
47+
public boolean containsNearbyDuplicate(int[] nums, int k) {
48+
Set<Integer> set = new HashSet<>();
49+
for (int i = 0; i < nums.length; i++) {
50+
if (!set.add(nums[i])) {
51+
return true;
52+
}
53+
if (set.size() > k) {
54+
set.remove(nums[i - k]);
55+
}
56+
}
57+
return false;
58+
}
59+
}
3160
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._219;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import static junit.framework.Assert.assertEquals;
8+
9+
public class _219Test {
10+
private static _219.Solution1 solution1;
11+
private static _219.Solution2 solution2;
12+
private static int[] nums;
13+
14+
@BeforeClass
15+
public static void setup() {
16+
solution1 = new _219.Solution1();
17+
solution2 = new _219.Solution2();
18+
}
19+
20+
@Test
21+
public void test1() {
22+
nums = new int[]{1, 2, 3, 1};
23+
assertEquals(true, solution1.containsNearbyDuplicate(nums, 3));
24+
}
25+
26+
@Test
27+
public void test2() {
28+
nums = new int[]{1, 2, 3, 1};
29+
assertEquals(true, solution2.containsNearbyDuplicate(nums, 3));
30+
}
31+
32+
}

0 commit comments

Comments
 (0)