comments | difficulty | edit_url | rating | source | tags | ||
---|---|---|---|---|---|---|---|
true |
中等 |
1375 |
第 15 场双周赛 Q2 |
|
给你一个区间列表,请你删除列表中被其他区间所覆盖的区间。
只有当 c <= a
且 b <= d
时,我们才认为区间 [a,b)
被区间 [c,d)
覆盖。
在完成所有删除操作后,请你返回列表中剩余区间的数目。
示例:
输入:intervals = [[1,4],[3,6],[2,8]] 输出:2 解释:区间 [3,6] 被区间 [2,8] 覆盖,所以它被删除了。
提示:
1 <= intervals.length <= 1000
0 <= intervals[i][0] < intervals[i][1] <= 10^5
- 对于所有的
i != j
:intervals[i] != intervals[j]
class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda x: (x[0], -x[1]))
cnt, pre = 1, intervals[0]
for e in intervals[1:]:
if pre[1] < e[1]:
cnt += 1
pre = e
return cnt
class Solution {
public int removeCoveredIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[0] - b[0] == 0 ? b[1] - a[1] : a[0] - b[0]);
int[] pre = intervals[0];
int cnt = 1;
for (int i = 1; i < intervals.length; ++i) {
if (pre[1] < intervals[i][1]) {
++cnt;
pre = intervals[i];
}
}
return cnt;
}
}
class Solution {
public:
int removeCoveredIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b) { return a[0] == b[0] ? b[1] < a[1] : a[0] < b[0]; });
int cnt = 1;
vector<int> pre = intervals[0];
for (int i = 1; i < intervals.size(); ++i) {
if (pre[1] < intervals[i][1]) {
++cnt;
pre = intervals[i];
}
}
return cnt;
}
};
func removeCoveredIntervals(intervals [][]int) int {
sort.Slice(intervals, func(i, j int) bool {
if intervals[i][0] == intervals[j][0] {
return intervals[j][1] < intervals[i][1]
}
return intervals[i][0] < intervals[j][0]
})
cnt := 1
pre := intervals[0]
for i := 1; i < len(intervals); i++ {
if pre[1] < intervals[i][1] {
cnt++
pre = intervals[i]
}
}
return cnt
}