LeetCode(220):存在重複元素 III Contains Duplicate III(Java)

2019.11.17 LeetCode 從零單刷個人筆記整理(持續更新)

github:https://github.com/ChopinXBP/LeetCode-Babel

之前其實通過HashSet做過一道 傳送門:存在重複元素II,但是這道升級版很不一樣,從尋找重複元素(target = num)變成了尋找在差在t範圍內的元素(num-t <= target <= num+t)。

需要藉助桶思想+哈希表+滑動窗口。

用哈希表設計多個以t+1爲桶容量的桶,桶劃分爲……[-(t+1),-1][0,t][t+1,2t+1]……(注意負數)。key爲桶id,value爲桶中的元素,每個時刻桶中僅會存在一個元素。

用滑動窗口法遍歷數組,若桶中已經存在元素,則其絕對值差必≤t;否則,檢查兩側的桶的元素與當前元素差的絕對值是否符合要求。最後,向新桶中添加元素,並且將窗口外的元素從桶中移除。


傳送門:存在重複元素 III

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.

給定一個整數數組,判斷數組中是否有兩個不同的索引 i 和 j,使得 nums [i] 和 nums [j] 的差的絕對值最大爲 t,並且 i 和 j 之間的差的絕對值最大爲 ķ。

示例 1:
輸入: nums = [1,2,3,1], k = 3, t = 0
輸出: true

示例 2:
輸入: nums = [1,0,1,1], k = 1, t = 2
輸出: true

示例 3:
輸入: nums = [1,5,9,1,5,9], k = 2, t = 3
輸出: false


import java.util.HashMap;
/**
 *
 * 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.
 * 給定一個整數數組,判斷數組中是否有兩個不同的索引 i 和 j,使得 nums [i] 和 nums [j] 的差的絕對值最大爲 t,並且 i 和 j 之間的差的絕對值最大爲 ķ。
 *
 */

public class ContainsDuplicateIII {
    //桶思想+哈希表+滑動窗口
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if (k < 1 || t < 0){
            return false;
        }
        HashMap<Long, Long> buckets = new HashMap<>();
        //滑動窗口
        for(int i = 0; i < nums.length; i++){
            long bucketIdx = getBucketID(nums[i], t);
            //若桶中已經存在元素,則其絕對值差必≤t
            if(buckets.containsKey(bucketIdx)){
                return true;
            }
            //否則檢查兩側的桶的元素與當前元素差的絕對值是否符合要求
            if(buckets.containsKey(bucketIdx - 1) && Math.abs(nums[i] - buckets.get(bucketIdx - 1)) <= t){
                return true;
            }
            if(buckets.containsKey(bucketIdx + 1) && Math.abs(nums[i] - buckets.get(bucketIdx + 1)) <= t){
                return true;
            }
            //向新桶中添加元素,並且將窗口外的元素從桶中移除
            buckets.put(bucketIdx, (long)nums[i]);
            if(i >= k){
                long oldBucketIdx = getBucketID(nums[i - k], t);
                buckets.remove(oldBucketIdx);
            }
        }
        return false;
    }

    //用哈希表設計多個以t+1爲桶容量的桶,桶劃分爲……[-(t+1),-1][0,t][t+1,2t+1]……(注意負數)。key爲桶id,value爲桶中的元素,每個時刻桶中僅會存在一個元素。
    private long getBucketID(long x, long t) {
        return x < 0 ? (x + 1) / (t + 1) - 1 : x / (t + 1);
    }
}



#Coding一小時,Copying一秒鐘。留個言點個讚唄,謝謝你#

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章