Leetcode 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] and nums[j] is at most t and the difference between i and j is at most k.


解题思路:

关键是要想到用TreeSet或者SortedSet, 而且要维护好k 的窗口!!!

另外,要考虑溢出情况,所以必须使用long !!!!

方法一: TreeSet 用的是Binary Search Tree, 有两个有用的method: ceiling() and floor(), the time complexity is O(nlog(k)).

ceiling() : Returns the least element in this set greater than or equal to the given element, or null if there is no such element.

floor() : Returns the greatest element in this set less than or equal to the given element, or null if there is no such element.

方法二: SortedSet 可以界定左边界和右边界。

两个方法的共同点是维护好k的窗口。


 Java code:

方法一:

 public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if(k < 1 || t < 0) {
            return false;
        }   
        TreeSet<Long> set = new TreeSet<Long>();
        for(int i= 0; i< nums.length; i++) {
            long x = (long)nums[i];
            if((set.floor(x) != null && (x-(long)(set.floor(x)) <=(long)t)) 
               || (set.ceiling(x)!=null && ((long)(set.ceiling(x))-x <=(long)t))) {
                return true;
            }
            set.add(x);
            if(i>=k) {
                set.remove((long)nums[i-k]);
            }
        }
        return false;
    }

方法二:

public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if(k < 1 || t < 0) {
            return false;
        }
        SortedSet<Long> set = new TreeSet<Long>();
        for(int i =0; i< nums.length; i++) {
            long leftBound = (long)nums[i]-t;
            long rightBound = (long)nums[i]+t+1;
            SortedSet<Long> subSet = set.subSet(leftBound, rightBound);
            if(!subSet.isEmpty()){
                return true;
            }
            set.add((long)nums[i]);
            if(i>=k) {
                set.remove((long)nums[i-k]);
            }
        }
        return false;
    }

Reference:

1. http://www.programcreek.com/2014/06/leetcode-contains-duplicate-iii-java/

 

posted @ 2015-09-22 02:19  茜茜的技术空间  阅读(323)  评论(0编辑  收藏  举报