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 jis at most k.
思路:本题分两种情况考虑,给的数组长度是否大于k。如果不大于k,则这需要看看里面是否有相同就行。
如果数组的长度大于k,那就判断在nums[i]到nums[i+k]中是否有相同的好
代码如下(已通过leetcode)
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(nums.length<=k+1) {
Set<Integer> s= new HashSet<Integer>();
for(int i=0;i<nums.length;i++) {
s.add(nums[i]);
}
if(s.size()!=nums.length) return true;
else return false;
}
else {
for(int i=0;i<nums.length;i++) {
for(int j=i+1;j<= i+k&&j<nums.length;j++) {
if(nums[i]==nums[j]) return true;
}
}
return false;
}
}
}