未验证 提交 eb8996ff 编写于 作者: X xshahq 提交者: GitHub

Add files via upload

上级 8309703e
# 56. Merge Intervals
**<font color=red>难度:Medium<font>**
## 刷题内容
> 原题连接
* https://leetcode.com/problems/merge-intervals/
> 内容描述
```
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
```
> 思路1
******- 时间复杂度: O(nlgn)******- 空间复杂度: O(1)******
这里我们要先对数组进行排序,按照start进行升序排序。接下来就遍历排序好的数组,如过不相交就将两个区间都存入ans。如果相交就将合并后的区间的并入ans。
```cpp
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval> ans;
if(!intervals.size())
return ans;
sort(intervals.begin(),intervals.end(),[](Interval a, Interval b){return a.start < b.start;});
for(int i = 0;i < intervals.size() - 1;++i)
if(intervals[i + 1].start <= intervals[i].end)
{
intervals[i + 1].start = intervals[i].start;
intervals[i].end = max(intervals[i].end,intervals[i + 1].end);
intervals[i + 1].end = intervals[i].end;
}
else
ans.push_back(intervals[i]);
ans.push_back(intervals[intervals.size() - 1]);
return ans;
}
};
```
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册