AdSense

Monday, October 3, 2016

Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] andnums[j] is at most t and the difference between i and j is at most k.

The problem is different from the first two, in fact, it's difficult for us to extend the approach in the previous two problems for this one. Here is a solution that I think is easy to understand. We use a treeset of size k. For every number in the array, we check if there is number existing in range n[i] - t to n[i] + t, if there exists one, or if there is a number that is the same as this one already exists in the set, we know we've found the number.  Remove all numbers with index has a difference with current one larger than k.


public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
/*handle special case*/
    if(nums.length <= 1 || t < 0 || k < 1) {return false;}
    TreeSet set = new TreeSet();
    for(int i = 0; i < nums.length; i++){
        long min = Math.min((long)nums[i] - t,(long)nums[i] + t + 1);
        long max = Math.max((long)nums[i] - t, (long)nums[i] + t + 1);
    /*1.if the subset is not empty, means that we have the element that satisfy the requirement 
      2.if we cannot add the element to the set, that means we already have the element*/
        if(!set.subSet(min,max).isEmpty() || !set.add((long)nums[i])) {return true;}
        set.add((long)nums[i]);
        if(i >= k) {set.remove((long)nums[i - k]);}
    }
    return false;
}


No comments:

Post a Comment