leetcode之Insert Interval 问题
2017-07-25 20:58
204 查看
问题描述:
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
示例:
Example 1:
Given intervals
Example 2:
Given
This is because the new interval
问题来源:Insert Interval (详细地址:https://leetcode.com/problems/insert-interval/#/description)
思路:可以归纳为以下两步:
(1)如果某一个interval的最大的数(即end值)比newInterval的最小值(即start值)要是还要小的话,那么他们肯定是没有交集的,则直接忽略它,不动它就可以了;
(2)如果它们有交集的话,则合并之后的interval的最小值(即start值)取它们中较小的一个,最大值(即end值)取它们中较大的一个即可。
(3)多啰嗦一句,在这你当然可以新生成一个list存放所有的新的intervals,但是考虑空间复杂度的话,我们没必要浪费多余的空间,所以可以直接采用原来的list存放intevals。
代码:
![](https://img-blog.csdn.net/20170725205739438?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveHUyNjQ1MzE4NDAw/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
示例:
Example 1:
Given intervals
[1,3],[6,9], insert and merge
[2,5]in as
[1,5],[6,9].
Example 2:
Given
[1,2],[3,5],[6,7],[8,10],[12,16], insert and merge
[4,9]in as
[1,2],[3,10],[12,16].
This is because the new interval
[4,9]overlaps with
[3,5],[6,7],[8,10].
问题来源:Insert Interval (详细地址:https://leetcode.com/problems/insert-interval/#/description)
思路:可以归纳为以下两步:
(1)如果某一个interval的最大的数(即end值)比newInterval的最小值(即start值)要是还要小的话,那么他们肯定是没有交集的,则直接忽略它,不动它就可以了;
(2)如果它们有交集的话,则合并之后的interval的最小值(即start值)取它们中较小的一个,最大值(即end值)取它们中较大的一个即可。
(3)多啰嗦一句,在这你当然可以新生成一个list存放所有的新的intervals,但是考虑空间复杂度的话,我们没必要浪费多余的空间,所以可以直接采用原来的list存放intevals。
代码:
相关文章推荐
- leetcode20: Insert Interval
- Leetcode Insert Interval
- Leetcode -- Insert Interval
- LeetCode Insert Interval
- LeetCode: Insert Interval
- LeetCode Insert Interval
- LeetCode 57 --- Insert Interval
- leetcode - Insert Interval
- Leetcode 57 Insert Interval
- leetcode Insert Interval
- Leetcode: Insert Interval
- [LeetCode] Insert Interval 二分搜索
- leetcode insert interval
- LeetCode: Insert Interval
- LeetCode Insert Interval
- leetcode20: Insert Interval
- LeetCode57 Insert Interval
- 【LeetCode with Python】 Insert Interval
- LeetCode() Insert Interval
- 《leetCode》:Insert Interval