题目:
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.
给出一个整形数组nums和一个整数k,判断是否存在nums[i]和nums[j],使nums[i]==nums[j],且i,j之间的差距不超过k值。
思路:
根据题意知,两个相等元素之间的距离最大为k,则可以通过Set进行查找,如果当前查找表set中已经有相等元素时,返回true,否则将当前元素添加入查找表set中。注意:由于set中的元素个数是从0开始添加到k,当新添加一个元素,使当前元素数量变为k+1时,需要删除查找表中的第1个元素,其值为nums[i-k]。
程序:
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
boolean result = false;
HashSet<Integer> record = new HashSet<Integer>();
for(int i = 0; i < nums.length; i++){
if(record.contains(nums[i]))
result = true;
record.add(nums[i]);
if(record.size() >= k+1)
record.remove(nums[i-k]);
}
return result;
}
}