[LeetCode 220] Contains Duplicat

2019-07-26  本文已影响0人  灰睛眼蓝

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

Example 1:

Input: nums = [1,2,3,1], k = 3, t = 0
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1, t = 2
Output: true

Example 3:

Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false

参考https://www.youtube.com/watch?v=yc4hCFzNNQc

Solution1: Brute force

Solution2: TreeSet (Binary Search Tree)

Input: nums = [11, 20, 5, 30 1], k = 3, t = 5
Output: true
  1. 遍历数组,每个遍历到的entry都找之前size为k个子数组中,比其大 和 比起小的两个数,看他们与当前数的差值是否小于t,一旦任何一个小于t,则符合题意,返回true
  2. 那么用什么数据结构可以快速找到比其大 和 比起小的两个数? TreeSet!!treeSet.ceiling (num) 和 treeset.floor (num)
  3. 由于题目限制了k,所以TreeSet中只需要存储k个值即可。
class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if (nums == null || nums.length == 0 || k <= 0 || t < 0)
            return false;
        
        //1. Solution 1: TreeSet (BST data structure)
        TreeSet<Integer> tracker = new TreeSet<> ();
        
        for (int i = 0; i < nums.length; i++) {
            Integer ceiling = tracker.ceiling (nums[i]);
            
            // the smallest number which is larger than nums[i]
            if (ceiling != null && Long.valueOf (ceiling) - Long.valueOf (nums[i]) <= t)
                return true;
            
            // the largest number which is smaller than nums[i]
            Integer floor = tracker.floor (nums[i]);
            if (floor != null && Long.valueOf (nums[i]) - Long.valueOf (floor) <= t)
                return true;
            
            tracker.add (nums[i]);
            
            if (i >= k) {
                tracker.remove (nums[i - k]);
            }
        }
        
        return false;
    }
}
上一篇下一篇

猜你喜欢

热点阅读