问题:给出若干区间,区间之间可能有交集。输出合并之后的区间。
例题
1.Merge Intervals
https://leetcode-cn.com/problems/merge-intervals/
思路
按照区间的左端点,右端点从小道大排序。遍历每一个区间,若当前区间curr.start <= last.end,证明区间有可能有交集,需要更新上一个区间last.end的值。若curr.start > last.end 证明两个区间不可能有交集。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Record {
int left, right;
};
bool cmp(Record a, Record b) {
if (a.left != b.left) {
return a.left < b.left;
}
else {
return a.right < b.right;
}
}
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
int n = intervals.size();
if (n == 0) {
return *(new vector<vector<int>>);
}
Record* rec = new Record[n];
for (int i = 0; i < n; i++) {
rec[i].left = intervals[i][0];
rec[i].right = intervals[i][1];
}
sort(rec, rec + n, cmp);
Record* ans = new Record[n];
int k = 0;
ans[k].left = rec[k].left;
ans[k].right = rec[k].right;
for (int curr = 1; curr < n; curr++) {
if (ans[k].right >= rec[curr].left&&rec[curr].right >ans[k].right) {
ans[k].right = rec[curr].right;
}
else if (ans[k].right < rec[curr].left) {
ans[++k].left = rec[curr].left;
ans[k].right = rec[curr].right;
}
}
vector < vector<int>>* ans_vc = new vector < vector<int>>;
for (int i = 0; i <= k; i++) {
vector<int>* temp = new vector<int>;
temp->push_back(ans[i].left);
temp->push_back(ans[i].right);
ans_vc->push_back(*temp);
}
return *ans_vc;
}
};
2.剩下的树
https://www.nowcoder.com/practice/f5787c69f5cf41499ba4706bc93700a2?tpId=40&tqId=21356&tPage=2&rp=1&ru=%2Fta%2Fkaoyan&qru=%2Fta%2Fkaoyan%2Fquestion-ranking
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct node
{
int left, right;
};
bool cmp(node a, node b) {
if (a.left != b.left) {
return a.left < b.left;
}
else {
return a.right < b.right;
}
}
int main()
{
//freopen("in.text", "r", stdin);
int n,m;
while (cin>>n>>m)
{
node* rec = new node[m];
for (int i = 0; i < m; i++)
{
cin >> rec[i].left >> rec[i].right;
}
sort(rec, rec + m, cmp);
vector<node> vc;
node temp;
temp.left = rec[0].left;
temp.right = rec[0].right;
vc.push_back(temp);
for (int curr = 1; curr < m; curr++)
{
int last = vc.size() - 1;
if (vc[last].right >= rec[curr].left && vc[last].right < rec[curr].right) {
vc[last].right = rec[curr].right;
}
else if(rec[curr].left>vc[last].right){
temp.left = rec[curr].left;
temp.right = rec[curr].right;
vc.push_back(temp);
}
}
int ans = (n + 1);
for (int i = 0; i < vc.size(); i++)
{
//cout << "[" << vc[i].left << "," << vc[i].right << "]" << endl;
ans -= (vc[i].right - vc[i].left + 1);
}
cout << ans << endl;
}
//fclose(stdin);
}