算法問題(查找表:Set,Map)--存在重複元素III

LeetCode第220號題–存在重複元素III

題目如下

給定一個整數數組,判斷數組中是否有兩個不同的索引 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

解答
這道題彷彿並未要求數組中有重複元素,在LeetCode中要求下面這組也需返回爲true

int[] nums = {2, 1};
int k = 1;
int t = 1;

並且此題會出現int值越界的問題,所以我們需要使用long類型,如下也需返回true

int[] nums = {0, 2147483647};
int k = 1;
int t = 2147483647;

解答如下

public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if (t < 0)
            return false;

        TreeSet<Long> record = new TreeSet<>();
        for (int i = 0; i < nums.length; i++) {
            //ceiling(E e) 方法返回在這個集合中大於或者等於給定元素的最小元素,如果不存在這樣的元素,返回null
            //查找表中是否有大於等於 nums[i] - t 且小於等於 nums[i] + t 的值
            if (record.ceiling((long)nums[i] - (long)t) != null && record.ceiling((long)nums[i] - (long)t) <= (long)nums[i] + (long)t)
                return true;

            record.add((long) nums[i]);

            //我們確保數據不超過k+1,使得兩數的差的絕對值不超過 k
            if (record.size() == k + 1)
                record.remove((long) nums[i - k]);
        }

        return false;
    }

類似問題:
LeetCode第217號題–存在重複元素
LeetCode第219號題–存在重複元素II

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