leetcode 原题链接: https://leetcode.com/problems/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 difference between i and j is at most k.
简要翻译:给定一个数组和一个整数k,找到两个各不相同的数字i和j 是的在数组中有nums[i] = nums[j] 并且i 和j 的差值不超过 k
简要分析:根据包含重复数字1 的内容,我这里也可以采用hashset的集合类来判断是否有重复数字,但是这其中还有另外一个要求 即| i - j | <= k。
这里我采用的是从数组区间里入手。即先取k+1个数,此时第一个数和最后一个数的索引差值最大,且为k。因此若此k+1个数中有重复数字,则说明此数组中存在题目中所要求的条件,返回true,否则继续查找,每次移动一位,将k+1个数中的第一个数从集合中删除,将降剩余数组的第一个数加入到集合中,保持数组一直都是k+1个数。当遍历到最后一个数字还未有满足要求的数字出现时,此时说明此数组中没有满足要求的数,返回false。
具体实现代码如下
public static boolean containsNearbyDuplicate(int[] nums, int k)
{
Set<Integer> set = new HashSet<Integer>();
if (k < nums.length)
{
for (int i = 0; i <= k; i++)
{
if (set.contains(nums[i]))
return true;
else
set.add(nums[i]);
}
for (int i = k+1; i < nums.length; i++)
{
set.remove(nums[i-k-1]);
if (set.contains(nums[i]))
return true;
else
set.add(nums[i]);
}
return false;
}else
{
for (int i = 0; i < nums.length; i++)
{
if (set.contains(nums[i]))
return true;
else
set.add(nums[i]);
}
return false;
}
}
ps:需要说明的是,虽然题目没有明说,但是我认为,k值有可能会大于等于数组的长度,此时需要另作讨论。因此我在实现的过程中进行了分类讨论操作。