【LeetCode】220. Contains Duplicate III

Difficulty:easy

 More:【目錄】LeetCode Java實現html

Description

https://leetcode.com/problems/contains-duplicate-iii/java

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 tand the absolute difference between i and j is at most k.post

Example 1:ui

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

Example 2:spa

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

Example 3:code

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

Intuition

1. treeSethtm

2. bucket ( bucket's size = t )blog

 

Solution

TreeSetip

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

 

bucket:leetcode

    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if(nums==null || k<0 || t<0)
            return false;
        HashMap<Long, Integer> map = new HashMap<>();
        for(int i=0; i<nums.length; i++){
            if(map.size()>k){     //下標差值不能大於k
                long lastBucket = ((long)nums[i-k-1]-Integer.MIN_VALUE)/((long)t+1);   // 以訪k=5時,-4和4放在同一個bucket中,致使結果錯誤
                map.remove(lastBucket);
            }
            long bucket = ((long)nums[i]-Integer.MIN_VALUE)/((long)t+1);    //t+1也必須轉爲long類型,以訪t=MAX_VALUE時,超出範圍
            if(map.containsKey(bucket)||
              (map.containsKey(bucket-1) && (long)nums[i]-map.get(bucket-1)<=t )||   //bucket的數字比bucket-1的大,因此不用比較>=-t
              (map.containsKey(bucket+1) && (long)map.get(bucket+1)-nums[i]<=t))     //轉換爲long類型以防差值超出Integer範圍
                return true;
            map.put(bucket,nums[i]);
        }
        return false;
    }

  

Complexity

TreeSet: 

  Time complexity : O(nlog(min(n,k)))

  Space complexity : O(min(n,k))

 Bucket:

  Time complexity : O(n)

  Space complexity : O(k)

 

What I've learned

1. treeSet.ceiling(e) && treeSet.floor(e) 

2. Pay attention to overflow problems: difference of two values may smaller than Integer.MIN_VALUE or bigger than Integer.MAX_VALUE.

 

 More:【目錄】LeetCode Java實現

相關文章
相關標籤/搜索