问题描述:
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.
分析:起初我能想到的就是使用二二比较的方法进行比对,如果相同返回true,虽然可以AC,但是时间很长。
代码如下:1344ms
bool containsNearbyDuplicate(int* nums, int numsSize, int k) {
int slow=0,fast=0;
for(slow = 0;slow<numsSize;slow++){
for(fast = slow+1;fast<=slow+k && fast<numsSize;fast++)
if(nums[slow] == nums[fast])
return true;
}
return false;
}
使用hashset来存储k个数据,时间复杂度为O(n)
代码如下:416ms
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashSet<Integer> sets = new HashSet<>();
int slow = 0;
for(int fast = 0;fast<nums.length;fast++){
if(fast-slow>k)
sets.remove(nums[slow++]);
if(sets.contains(nums[fast]))
return true;
sets.add(nums[fast]);
}
return false;
}
}