Problem
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.
Example
Given nums = [1,2,1], k = 0, return false.
Solution
public class Solution {
/**
* @param nums: the given array
* @param k: the given number
* @return: 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
*/
public boolean containsNearbyDuplicate(int[] nums, int k) {
// Write your code here
if (nums.length < 2 || k < 1) return false;
Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
// i - (i-k-1) > k
if (i > k) set.remove(nums[i-k-1]);
if (set.contains(nums[i])) return true;
set.add(nums[i]);
}
return false;
}
}
也可以用HashMap的简单解法
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。