- 排序, start升序,end降序 (贪心思想)
- 画图
- 区间有三种情况:覆盖、相交、不相交
1. 线段区间
```cpp // [s1, e1] 、 [s2, e2] // 相交 int start = max(s1, s2); int end = min(e1, e2); if (start <= end) { return true; // 有交集 }
if (e1 >= e2) { // 覆盖 } else if (e1 < s2) { // 不相交 } else { // 相交 }
// 1288.删除被覆盖区间
class Solution {
public:
static bool cmp(vector
int removeCoveredIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), cmp);
int start = intervals[0][0];
int end = intervals[0][1];
int count = -1;
for (auto &it: intervals) {
// 覆盖
if (start <= it[0] && end >= it[1]) {
count++;
} else if (end >= it[0]) { // 相交
end = max(end, it[1]);
} else {
start = it[0];
end = it[1];
}
}
return intervals.size() - count;
}
};
// 56.合并区间
class Solution {
public:
static bool cmp(vector
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), cmp);
vector<vector<int>> ans;
int start = intervals[0][0];
int end = intervals[0][1];
for (int i = 1; i < intervals.size(); i++) {
// 重叠,或者覆盖
if (end >= intervals[i][0]) {
end = max(end, intervals[i][1]);
} else {
ans.push_back({start, end});
start = intervals[i][0];
end = intervals[i][1];
}
}
ans.push_back({start, end});
return ans;
}
};
// 986.区间列表的交集
class Solution {
public:
vector
vector<vector<int>> ans;
int i = 0;
int j = 0;
while (i < firstList.size() && j < secondList.size()) {
// 求交集,小技巧
int start = max(firstList[i][0], secondList[j][0]);
int end = min(firstList[i][1], secondList[j][1]);
if (start <= end) {
ans.push_back({start, end});
}
// 需要注意指针的移动
if (firstList[i][1] < secondList[j][1]) {
i++;
} else {
j++;
}
}
return ans;
}