Skip to content

Commit 0291954

Browse files
contains duplicate II
1 parent b396769 commit 0291954

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package easy;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
/**219. Contains Duplicate II QuestionEditorial Solution My Submissions
7+
Total Accepted: 69920
8+
Total Submissions: 228733
9+
Difficulty: Easy
10+
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.*/
11+
public class ContainsDuplicateII {
12+
//pretty straightforward, use a hashmap, key is the number itself, value is the last index that this value appeared in the array
13+
//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
14+
//the later indices won't even do either. So, we only need to keep one index in the value of the HashMap. Cheers!
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) return true;
20+
else map.put(nums[i], i);
21+
}
22+
else map.put(nums[i], i);
23+
}
24+
return false;
25+
}
26+
}

0 commit comments

Comments
 (0)