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<Integer,List<Integer>>来记录所有的重复元素的index,其实没必要,只要记录最后一次index的坐标即可,然后做判断,因为是从后往前扫描的。
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(nums == null || nums.length <2) return false;
HashMap<Integer, Integer> hashmap = new HashMap<Integer, Integer>();
for(int i=0; i< nums.length; i++) {
if(!hashmap.containsKey(nums[i])){
hashmap.put(nums[i], i);
} else {
if( i - hashmap.get(nums[i]) <=k ) {
return true;
}else {
hashmap.put(nums[i],i);
}
}
}
return false;
}
}