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)插入的区间段小于原来的第一个区间段
(3)插入的区间段大于原来的最后一个区间段
(4)找到插入区间开始和结束位置在原来的有序区间段的索引位置,找开始位置时,如果没有找到,就以大于开始位置的索引为准。而在找结束位置时,如果没有找到, 就以小于结束位置的索引为准
代码如下:
class Solution { public List<Interval> insert(List<Interval> intervals, Interval newInterval) { List<Interval> ans = new ArrayList<Interval>(); int size = intervals.size(); if (0 == size) { ans.add(newInterval); return ans; } if (newInterval.end < intervals.get(0).start) { ans.add(newInterval); ans.addAll(intervals); return ans; } else if (newInterval.start > intervals.get(size - 1).end) { ans.addAll(intervals); ans.add(newInterval); return ans; } int index1 = 0, index2 = size - 1; for (int i = 0; i < size; i++) { Interval cur = intervals.get(i); if (newInterval.start >= cur.start && newInterval.start <= cur.end) { index1 = i; } else if (i != size - 1) { Interval next = intervals.get(i + 1); if (newInterval.start > cur.end && newInterval.start < next.start) { index1 = i + 1; } } if (newInterval.end >= cur.start && newInterval.end <= cur.end) { index2 = i; } else if (i != size - 1) { Interval next = intervals.get(i + 1); if (newInterval.end > cur.end && newInterval.end < next.start) { index2 = i; } } } for (int i = 0; i < index1; i++) { Interval cur = intervals.get(i); ans.add(cur); } Interval tmp = new Interval(); tmp.start = Math.min(intervals.get(index1).start, newInterval.start); tmp.end = Math.max(intervals.get(index2).end, newInterval.end); ans.add(tmp); for (int i = index2 + 1; i < size; i ++) { Interval cur = intervals.get(i); ans.add(cur); } return ans; } }