import org.omg.CORBA.INTERNAL;
import java.util.Set;
import java.util.TreeSet;
/**
* @author xnl
* @Description:
* @date: 2022/7/9 22:26
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
}
/**
* 超时,不行
*
* @param nums
* @param k
* @param t
* @return
*/
public boolean containsNearbyAlmostDuplicate2(int[] nums, int k, int t) {
int n = nums.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
long x = nums[i];
long y = nums[j];
if (i != j && Math.abs(x - y) <= t && Math.abs(i - j) <= k) {
return true;
}
}
}
return false;
}
/**
* 滑动指针
*
* @param nums
* @param k
* @param t
* @return
*/
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 u = nums[i] * 1L;
Long l = treeSet.floor(u);
Long r = treeSet.ceiling(u);
if (l != null && u - l <= t) {
return true;
}
if (r != null && r - u <= t){
return true;
}
treeSet.add(u);
if (i >= k){
treeSet.remove(nums[i - k] * 1L);
}
}
return false;
}
}
力扣:220. 存在重复元素 III
最新推荐文章于 2024-07-09 16:17:35 发布