# 合并区间
以数组 intervals
表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi]
。请你合并所有重叠的区间,并返回一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间。
示例 1:
输入:intervals = [[1,3],[2,6],[8,10],[15,18]]
输出:[[1,6],[8,10],[15,18]]
解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
示例 2:
输入:intervals = [[1,4],[4,5]]
输出:[[1,5]]
解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。
提示:
1 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti <= endi <= 104
以下错误的选项是?
## aop
### before
```cpp
#include
using namespace std;
```
### after
```cpp
```
## 答案
```cpp
class Solution
{
public:
vector> merge(vector> &intervals)
{
vector> res;
sort(intervals.begin(), intervals.end(), [](const auto &u, const auto &v)
{
if (u[0] == v[0])
return u[1] > v[1];
else
return u[0] < v[0];
});
auto it = intervals.begin();
int first = (*it)[0], second = (*it)[1];
for (it++; it != intervals.end(); it++)
{
if ((*it)[0] <= second)
second = max(second, (*it)[0]);
else
{
res.push_back({first, second});
first = (*it)[0];
second = (*it)[1];
}
}
res.push_back({first, second});
return res;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector> merge(vector> &intervals)
{
vector> res;
sort(intervals.begin(), intervals.end());
for (auto it = intervals.begin(); it != intervals.end(); it++)
{
int first = (*it)[0], second = (*it)[1];
if (!res.size() || res.back()[1] < first)
res.push_back({first, second});
else
res.back()[1] = max(res.back()[1], second);
}
return res;
}
};
```
### B
```cpp
class Solution
{
public:
vector> merge(vector> &intervals)
{
sort(intervals.begin(), intervals.end());
vector> res;
for (int i = 0; i < intervals.size();)
{
int t = intervals[i][1];
int j = i + 1;
while (j < intervals.size() && intervals[j][0] <= t)
{
t = max(t, intervals[j][1]);
j++;
}
res.push_back({intervals[i][0], t});
i = j;
}
return res;
}
};
```
### C
```cpp
class Solution
{
public:
static bool cmp(const vector &a, const vector &b)
{
if (a[0] == b[0])
return a[1] > b[1];
return a[0] < b[0];
}
vector> merge(vector> &intervals)
{
if (intervals.empty())
return intervals;
vector> res;
int count = 0;
sort(intervals.begin(), intervals.end(), cmp);
vector temp;
temp.push_back(intervals[0][0]);
temp.push_back(intervals[0][1]);
res.push_back(temp);
for (int i = 1; i < intervals.size(); i++)
{
if (res[count][1] >= intervals[i][0])
{
if (res[count][1] <= intervals[i][1])
{
res[count][1] = intervals[i][1];
}
}
else
{
count++;
temp[0] = intervals[i][0];
temp[1] = intervals[i][1];
res.push_back(temp);
}
}
return res;
}
};
```