Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.
要求用hashtable或者hashset实现,自己用两个for循环实现的,显然效率差别大,因此我的答案依然是tiime limit exceeded.改用hashset之后accepted。传统的思想:
public boolean containsNearbyDuplicate(int[] nums, int k) {
// %find nums[i]=nums[j]
int num_flag=0;
for(int i=0;i<nums.length;i++)
for(int j=nums.length-1;j>i;j--)
{
if(nums[i]==nums[j] && Math.abs(i-j)>k)
num_flag++;
}
if(num_flag>0)
return true;
else
return false;
}
采用hash和游标之后的结果:
public boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> appearedNum = new HashSet<Integer>();
int start = 0, end = 0;
for(int i = 0; i < nums.length; i++){
//如果hashset中不包含数组nums的值,将其加入hashset中,end自增
if(!appearedNum.contains(nums[i])){
appearedNum.add(nums[i]);
end++;
} else return true;
//确保数组下标的间距大于k
if(end - start > k) {
appearedNum.remove(nums[start]);
start++;
}
}
return false;