219. Contains Duplicate II
又是很简单的题,不说什么了
1 public boolean containsNearbyDuplicate(int[] nums, int k) { 2 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 3 for(int i = 0; i < nums.length; i++) { 4 if(!map.containsKey(nums[i])) { 5 map.put(nums[i], i); 6 } else { 7 if(i - map.get(nums[i]) <= k) { 8 return true; 9 } 10 map.put(nums[i], i); 11 } 12 } 13 return false; 14 }
有个很好看的解法:
1 public boolean containsNearbyDuplicate(int[] nums, int k) { 2 Set<Integer> set = new HashSet<Integer>(); 3 for(int i = 0; i < nums.length; i++){ 4 if(i > k) set.remove(nums[i-k-1]); 5 if(!set.add(nums[i])) return true; 6 } 7 return false; 8 }
只用hashSet, 每次都记得把距离k以外的数去掉,只要查到就是true