Skip to content

Commit 99e4cac

Browse files
refactor 219
1 parent 6ea8b22 commit 99e4cac

File tree

1 file changed

+16
-14
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+16
-14
lines changed

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

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,28 @@
44
import java.util.Map;
55

66
/**219. Contains Duplicate II
7-
*
8-
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 difference between i and j is at most k.*/
7+
8+
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+
*/
912
public class _219 {
1013

11-
//pretty straightforward, use a hashmap, key is the number itself, value is the last index that this value appeared in the array
12-
//we can keep updating the value as we move forward, since if the current index minus the last index cannot be smaller than k, then
13-
//the later indices won't even do either. So, we only need to keep one index in the value of the HashMap. Cheers!
14-
public boolean containsNearbyDuplicate(int[] nums, int k) {
15-
Map<Integer, Integer> map = new HashMap();
16-
for (int i = 0; i < nums.length; i++) {
17-
if (map.containsKey(nums[i])) {
18-
if (i - map.get(nums[i]) <= k) {
19-
return true;
14+
public static class Solution1 {
15+
public boolean containsNearbyDuplicate(int[] nums, int k) {
16+
Map<Integer, Integer> map = new HashMap();
17+
for (int i = 0; i < nums.length; i++) {
18+
if (map.containsKey(nums[i])) {
19+
if (i - map.get(nums[i]) <= k) {
20+
return true;
21+
} else {
22+
map.put(nums[i], i);
23+
}
2024
} else {
2125
map.put(nums[i], i);
2226
}
23-
} else {
24-
map.put(nums[i], i);
2527
}
28+
return false;
2629
}
27-
return false;
2830
}
2931
}

0 commit comments

Comments
 (0)