floor(E e) 方法返回在这个集合中小于或者等于给定元素的最大元素,如果不存在这样的元素,返回null.
ceiling(E e) 方法返回在这个集合中大于或者等于给定元素的最小元素,如果不存在这样的元素,返回null.
给定一个整数数组,判断数组中是否有两个不同的索引 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值最大为 t,并且 i 和 j 之间的差的绝对值最大为 ?。
java 中TreeSet是自平衡二叉搜索树
如果窗口中维护的元素是有序的,只需要用二分搜索检查条件二是否是满足的就可以了。利用自平衡二叉搜索树,可以在对数时间内通过 插入 和 删除 来对滑动窗口内元素排序。
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { TreeSet<Integer> set = new TreeSet<>(); for (int i = 0; i < nums.length; ++i) { // Find the successor of current element Integer s = set.ceiling(nums[i]); if (s != null && s <= nums[i] + t) return true; // Find the predecessor of current element Integer g = set.floor(nums[i]); if (g != null && nums[i] <= g + t) return true; set.add(nums[i]); if (set.size() > k) { set.remove(nums[i - k]); } } return false; }
原文:https://www.cnblogs.com/zzm96/p/12336685.html