Given a list of intervals, remove all intervals that are covered by another interval in the list. Interval [a,b)
is covered by interval [c,d)
if and only if c <= a
and b <= d
.
After doing so, return the number of remaining intervals.
Example 1:
Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
Constraints:
1 <= intervals.length <= 1000
0 <= intervals[i][0] < intervals[i][1] <= 10^5
intervals[i] != intervals[j]
for alli != j
思路:核心思想就是:算overlap了多少个,然后用总个数减去overlap的个数。如何计算overlap就是:sort array , 首先按照x sort,如果x相同,y按照从大到小sort,这样只有前面的能够cover后面的,后面的不能cover前面的,因为x都排序了,y是按照从大到小排序的。
class Solution {
public int removeCoveredIntervals(int[][] intervals) {
if(intervals == null || intervals.length == 0) {
return 0;
}
int[] last = null;
Arrays.sort(intervals, (a, b) -> (a[0] != b[0] ? a[0] - b[0] : b[1] - a[1]));
int count = 0;
for(int[] interval : intervals) {
if(last == null) {
last = interval;
} else {
if(last[1] >= interval[1]) {
count++;
} else {
last = interval;
}
}
}
return intervals.length - count;
}
}