1288. Remove Covered Intervals
T: O(nlogn)
S: O(1)class Solution {
public int removeCoveredIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[0] != b[0] ? a[0] - b[0] : b[1] - a[1]);
int prevEnd = 0;
int res = 0;
for (int[] interval : intervals) {
if (interval[1] > prevEnd) { // not covered case
res++;
prevEnd = interval[1]; // so preEnd is the new end (not covered case, 獨立的)
}
}
return res;
}
}
/*
[[1, 4],
[3, 6],
[2, 8]]
[[1, 4],
[2,3]]
The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.
1.
[[1, 4],
[2, 8]]
[3, 6], -> cover: interval[1] (6) <= prevEnd (8)
becuase sort start, so start will asc
so covered case is => new end <= prev end
=> so not covered case is:
when new end > prev end => do result++ and update prevEnd = new end
2.
but there is a edge case, when start is the same
like this, => new end > prev end, res++ will fail, actually it's covered
|----|
|------|
res ++ means no cover, so no merge, so add intervals,
in this case, fail to detect there is a cover, so res++
so trick way is when start is same, do end sort desc
=> become this, so new end > prev end works!
|------|
|----|
detect there is a cover, so dont do res++
[[1, 4],
[2, 8]]
[3, 6],
4, 5
T:O(nlogn)
S: O(1)
*/new - this style also work for 2345
latest version:
Last updated
Was this helpful?