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.
Summary:
Firstly, i considerd the HashSet,but i ran into a problem that i can’t get the indecies of element. Then , i gave it off. Afterwards, i tried to use List,Map ,Array. The complexities of those is too high. Finally, i asked for a favor in the internet and completed my solution.
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
int start = 0;
int end = 0;
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < nums.length ; i++){
if(set.add(nums[i])){
end++;
}else{
return true;
}
if(end - start > k){
set.remove(nums[start]);
start++;
}
}
return false;
}
}