MCPcopy
hub / github.com/qiyuangong/leetcode / containsNearbyDuplicate

Method containsNearbyDuplicate

java/219_Contains_Duplicate_II.java:9–43  ·  view source on GitHub ↗
(int[] nums, int k)

Source from the content-addressed store, hash-verified

7 */
8
9 public boolean containsNearbyDuplicate(int[] nums, int k) {
10 HashMap<Integer, List<Integer>> map = new HashMap<>();
11
12 for(int i = 0; i < nums.length; i++) {
13 if(!map.containsKey(nums[i])) {
14 map.put(nums[i], new ArrayList<>());
15 }
16 map.get(nums[i]).add(i);
17 }
18
19 // use Iterator to find appropriate two indice.
20 // Each list guarantee ascending.
21 // So list.get(i) and list.get(i + 1) is minimum.
22 Iterator<Integer> keys = map.keySet().iterator();
23 boolean answer = false;
24
25 while(keys.hasNext()) {
26 int key = keys.next();
27 List<Integer> list = map.get(key);
28
29 if(list.size() < 2) continue;
30
31 for(int i = 1; i < list.size(); i++) {
32 int a = list.get(i - 1);
33 int b = list.get(i);
34
35 if(b - a <= k) {
36 answer = true;
37 break;
38 }
39 }
40 if(answer) break;
41 }
42 return answer;
43 }
44}

Callers

nothing calls this directly

Calls 5

containsKeyMethod · 0.80
nextMethod · 0.80
putMethod · 0.45
addMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected