Contains Duplicate II 解答

Question

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.

Solution -- HashMap

 public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
int length = nums.length;
if (length <= 1 || k < 1)
return false;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int min = Integer.MAX_VALUE;
for (int i = 0; i < length; i++) {
if (map.containsKey(nums[i])) {
int prev = map.get(nums[i]);
int gap = i - prev;
min = Math.min(min, gap);
}
map.put(nums[i], i);
}
if (min <= k)
return true;
else
return false;
}
}
上一篇:UWP图片编辑器(涂鸦、裁剪、合成)


下一篇:不可或缺 Windows Native (19) - C++: 对象的动态创建和释放, 对象的赋值和复制, 静态属性和静态函数, 类模板