Leetcode - 57 Insert Interval 解题报告
2017-02-14 06:47 Mux1 阅读(219) 评论(0) 编辑 收藏 举报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]
.
分析:
1. 这道题分成2个部分, 简单的部分是在newInterval 外侧的剩余intervals, 可以用两个while语句加到result中.
2. 本题难点在于如何把夹在中间的interval合并在一起 :
基本思想在于iterating, 把newInterval依次与夹在newInterval内的小interval合并 并且同时变成中间相(这里方便起见可以替换原来的newInterval),直到 newInterval.end小于某一个intervals.get(i).end. 然后加入到result中
代码: