(int[] nums, int k)
| 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 | } |
nothing calls this directly
no test coverage detected