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.
解法1: TreeSet, O(nlog(k, n))
这里用到一个比较特殊的数据结构treeset。
实际上这是一个self-balancing binary search tree, 他的基本操作都是O(logN)的。而且他还有两个额外的功能很有用
set.ceiling(T)和set.floor(T)
ceiling返回的是大于等于T的最小的元素,而floor返回的是小于等于T的最大元素。
那么我们维护一个大小为k的set,这样就满足了一个条件。
那第二个条件满足的条件就是对于每一个num,找出他的ceiling和floor,看是否在范围内即可。
解法2: O(N) using Bucket
|
|