美文网首页
220. Contains Duplicate III

220. Contains Duplicate III

作者: FlynnLWang | 来源:发表于2016-12-27 02:12 被阅读0次

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)

相关文章

网友评论

      本文标题:220. Contains Duplicate III

      本文链接:https://www.haomeiwen.com/subject/xaysvttx.html