219. Contains Duplicate II

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 absolute difference between i and j is at most k.

解法1:O(N) Time + O(N) Space

用一个HashMap来存储每一个number出现的位置。然后对于所有出现过两次以上的数字计算是否有满足的答案。
Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (nums == null || nums.length == 0) {
return false;
}
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
for (int i = 0; i < nums.length; ++i) {
if (map.containsKey(nums[i])) {
map.get(nums[i]).add(i);
} else {
map.put(nums[i], new ArrayList<Integer>());
map.get(nums[i]).add(i);
}
}
// traverse the HashMap
for (int num : map.keySet()) {
if (map.get(num).size() >= 2) {
List<Integer> indices = map.get(num);
// traverse the list
for (int i = 0; i < indices.size() - 1; ++i) {
if (indices.get(i + 1) - indices.get(i) <= k) {
return true;
}
}
}
}
return false;
}
}