LeetCode:Contains Duplicate II
Total Accepted: 42592 Total
Submissions: 148608 Difficulty: Easy
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 jis at most k.
Hide Tags
Hide Similar Problems
思路:
1.用map将数组前k个元素放入;
2.放第k+1个元素的时候,第1个元素就能够删除了。
由于第1个与第k+1个元素之间的距离已经达到k,它们肯定不符合要求,
这样保存了map中始终仅仅有k个元素;
3.再往后加入元素的时候发现(中原有的k个元素中)已经包括。返回true;
4.最后返回false。
code:
public class Solution { 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; } }