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.
这道题还是很简单的。没啥可说的。直接用hashmap就可以做了,借助containsKey(),get()还有put()。
代码如下。~
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer,Integer>test=new HashMap<>();
for(int i=0;i<nums.length;i++){
if(test.containsKey(nums[i])){
int diff=i-test.get(nums[i]);
if(diff<=k){
return true;
}
}
test.put(nums[i],i);
}
return false;
}
}