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.
使用map記錄元素出現(xiàn)的位置,再次出現(xiàn)時,比較一下這次的位置和上次的位置之差是否小于等于k。是就可以返回了,不是就將舊的記錄換成新的。
var containsNearbyDuplicate = function(nums, k) {
var num = nums.length;
if (num===0)
return false;
var map = {};
for (var i = 0; i < num; i++) {
if (map[nums[i]]!==undefined&&(i-map[nums[i]])<=k)
return true;
map[nums[i]] = i;
}
return false;
};
在有Set數(shù)據(jù)結(jié)構(gòu)的語言中,使用Set會更快:
這里相當(dāng)于使用set判斷一個k范圍內(nèi)是否有重復(fù)的數(shù),然后將這個范圍從頭移到尾。
public boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < nums.length; i++){
if(i > k) set.remove(nums[i-k-1]);
if(!set.add(nums[i])) return true;
}
return false;
}