2817. Minimum Absolute Difference Between Elements With Constraint
T: O(nlogn)
S: O(n)
```java
class Solution {
public int minAbsoluteDifference(List<Integer> nums, int x) {
TreeSet<Integer> set = new TreeSet<>();
int result = Integer.MAX_VALUE;
for (int i = x; i < nums.size(); i++) { // 反方向來想
set.add(nums.get(i-x)); // record legal value(>= x), add more and more
int cur = nums.get(i);
Integer ceiling = set.ceiling(cur);
if (ceiling != null) {
result = Math.min(result, ceiling - cur);
}
Integer floor = set.floor(cur);
if (floor != null) {
result = Math.min(result, cur - floor);
}
}
return result;
}
}
/*
T: O(nlogn)
S: O(n)
原本思路是
i >= x + j
x
i-------j
每次我都從後面所有的值(相距x)來找
但這樣我要先算出後面所有的, 爾且每次都要移除小於距離x的...
其實照著 i - j >= x 來想
反過來想的話, 變成 i 是 fast pointer, j 是 slow pointer
可以發現, 這樣每次新加入到 TreeSet 的, 都是合法的搜尋對象!
(因為距離都>=x, 如果 i, j 一開始就相距x , 所以之後 i 變大, 這x只會更大, 所以都是搜尋的候選人)
x
j----i
legal---|
so when i move to right, we'll have "more" legal value
they are all i - j >= x
i - j diff only will become bigger, not smaller, so we can use all the vaules save in Treeset
x
j----i
legal---|
*/
```
Last updated