Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list.
The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.
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.
Example 2:
Input: intervals = [[1,4],[2,3]]
Output: 1
给出二维数组,里面每一个元素都是一个区间,返回一共有多少个不重叠的区间。
区间重叠是指起点和终点覆盖了另一个区间。
思路:
因为区间重叠是指
The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.
按区间的起点大小排序,这样就满足了c <= a,只需要看终点b <= d
当然终点要从大往小看,因为先看大的,后面的比它小,就是在一个区间里。遇见比当前大的终点,就说明是一个新的区间。
public int removeCoveredIntervals(int[][] intervals) {
int result = 0;
int end = -1;
int n = intervals.length;
//按起点大小升序排序,如果起点大小相同,按终点降序排序
Arrays.sort(intervals, (o1, o2)->o1[0] == o2[0] ? o2[1] - o1[1] : o1[0] - o2[0]);
for(int[] interval : intervals) {
if(end < interval[1]) {
result ++;
end = interval[1];
}
}
return result;
}