问题描述:
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。
代码: