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]
.
When we meet an interval intersect with the current merged interval, we update the start and end accordingly. The initial state of the merged interval is the start and end of the new interval. A corner case is that the interval is inserted into the end of the list or it merged all interval in the list. In this case we need to check if we have ever insert the merged interval into the list.
public List<Interval> insert(List<Interval> intervals, Interval newInterval) { List<Interval> res = new ArrayList<Interval>(); int startTime = newInterval.start, endTime = newInterval.end; boolean merged = false; for(Interval i : intervals) { if(i.end < startTime) { res.add(i); } else if(i.start > endTime) { if(merged == false) { Interval interval = new Interval(startTime, endTime); res.add(interval); merged = true; } res.add(i); } else { startTime = Math.min(startTime, i.start); endTime = Math.max(endTime, i.end); } } if(merged == false) { Interval interval = new Interval(startTime, endTime); res.add(interval); merged = true; } return res; }
没有评论:
发表评论