[刷题防痴呆] 0220 - 存在重复元素III (Contai

2021-12-23  本文已影响0人  西出玉门东望长安

题目地址

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

题目描述

220. 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 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

思路

维护一个sliding window. 来不停判断 abs diff.

关键点

代码


// O(n2) TLE
class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j <= i + k && j < nums.length; j++) {
                if (Math.abs((long)nums[i] - (long)nums[j]) <= t) {
                    return true;
                }
            }
        }
        
        return false;
    }
}

// 红黑树做法 TreeSet O(nlogk)
class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        int n = nums.length;
        TreeSet<Long> treeSet = new TreeSet<>();
        for (int i = 0; i < n; i++) {
            Long num = nums[i] * 1L;
            Long left = treeSet.floor(num);
            Long right = treeSet.ceiling(num);
            if (left != null && num - left <= t) {
                return true;
            }
            if (right != null && right - num <= t) {
                return true;
            }
            treeSet.add(num);
            if (i >= k) {
                treeSet.remove(nums[i - k] * 1L);
            }
        }

        return false;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读