Sunday, September 17, 2017

219. Contains Duplicate II



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.

Solution: 
It is the extension of  217. Contains Duplicate
I will use hashset again to store all visited element, and remove element that are outside of K range. eg for element 0 doesn't affect element K+1... 
Some other methods like using Hashmap to store the index, and calculate difference when there are duplicate.
 public boolean containsNearbyDuplicate(int[] nums, int k) {  
     HashSet<Integer> set=new HashSet<Integer>();  
     for(int i=0;i<nums.length;i++){  
       if(!set.add(nums[i])) return true;  
       if(i>=k) set.remove(nums[i-k]);  
     }  
     return false;  
   }  

No comments:

Post a Comment