220. Contains Duplicate III

Question

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

Code

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

Solution

使用TreeSet数据结构。

TreeSet数据结构(Java)使用红黑树实现,是平衡二叉树的一种。

该数据结构支持如下操作:

  1. floor()方法返set中≤给定元素的最大元素;如果不存在这样的元素,则返回 null。

  2. ceiling()方法返回set中≥给定元素的最小元素;如果不存在这样的元素,则返回 null。

有个容易bug的地方

n <= t+set.floor(n)

不能写成n - t <= set.floor(n)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容