Tuesday, June 16, 2015

219. Contains Duplicate II

Q:
Given an array of integers and an integer k, find out whether there 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.
A:
就是简单的,在  k+1的长度中查询 duplicate

public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Set<Integer> set = new HashSet();
        for(int i =0;i< nums.length;i++){
            if(i - k - 1 >=0)   // delete first
                set.remove( nums[i-k-1]);
            
            if(set.contains(nums[i]))
                return true;
            set.add(nums[i]);
        }
        return false;
    }
}
 

No comments:

Post a Comment