Skip to content
体验新版
项目
组织
正在加载...
登录
切换导航
打开侧边栏
OpenDocCN
awesome-algorithm
提交
eb8996ff
A
awesome-algorithm
项目概览
OpenDocCN
/
awesome-algorithm
通知
1
Star
0
Fork
0
代码
文件
提交
分支
Tags
贡献者
分支图
Diff
Issue
0
列表
看板
标记
里程碑
合并请求
0
Wiki
0
Wiki
分析
仓库
DevOps
项目成员
Pages
A
awesome-algorithm
项目概览
项目概览
详情
发布
仓库
仓库
文件
提交
分支
标签
贡献者
分支图
比较
Issue
0
Issue
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
Pages
分析
分析
仓库分析
DevOps
Wiki
0
Wiki
成员
成员
收起侧边栏
关闭侧边栏
动态
分支图
创建新Issue
提交
Issue看板
前往新版Gitcode,体验更适合开发者的 AI 搜索 >>
未验证
提交
eb8996ff
编写于
3月 04, 2019
作者:
X
xshahq
提交者:
GitHub
3月 04, 2019
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
Add files via upload
上级
8309703e
变更
1
隐藏空白更改
内联
并排
Showing
1 changed file
with
62 addition
and
0 deletion
+62
-0
docs/Leetcode_Solutions/C++/0056._Merge_Intervals.md
docs/Leetcode_Solutions/C++/0056._Merge_Intervals.md
+62
-0
未找到文件。
docs/Leetcode_Solutions/C++/0056._Merge_Intervals.md
0 → 100644
浏览文件 @
eb8996ff
# 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.
先完成此消息的编辑!
取消
想要评论请
注册
或
登录