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 absolute difference between i and j is at most k.這道題目的意思是:輸入一個整數數組和一個整數k,若是數組中存在相等的兩個數,並且他們的位置差不超過k,那麼返回true,不然返回false數組
int length = nums.length; if(length<=1) return false; Set<Integer> count = new HashSet<Integer>(); for(int i=0;i<length;i++){ if(i > k){ count.remove(nums[i-k-1]); } if(!count.add(nums[i])){ return true; } } return false;