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:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]]
Example 2:
Input: intervals =[[1,2],[3,5],[6,7],[8,10],[12,16]]
, newInterval =[4,8]
Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval[4,8]
overlaps with[3,5],[6,7],[8,10]
.
感觉要解这种题,首先要迅速对可能出现的情况进行分类,比如这道题可以分三类:
聪明的分类,对吧。然后中心思想是:
当当前的interval的end小于newInterval的start时,说明新的区间在当前遍历到的区间的后面,并且没有重叠,这意味着永远都和这个interval无关,所以res添加当前的interval;
当当前的interval的start大于newInterval的end时,说明新的区间比当前遍历到的区间要前面,并且也没有重叠,所以把newInterval添加到res里,和上面的原因类似,并更新newInterval为当前的interval,因为之后只有大的interval才能用上。
当当前的interval与newInterval有重叠时,merge interval并更新新的newInterval为merge后的。大大,小小
/** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ class Solution { public List<Interval> insert(List<Interval> intervals, Interval newInterval) { List<Interval> res= new ArrayList<Interval>(); int l = intervals.size(); for(Interval each : intervals){ if(each.end < newInterval.start){ res.add(each); } else if(newInterval.end < each.start){ res.add(newInterval); newInterval = each; } else if(newInterval.start <= each.end || each.start <= newInterval.end){ newInterval.start = (Math.min(newInterval.start, each.start)); newInterval.end = (Math.max(newInterval.end, each.end)); } } res.add(newInterval); return res; } }
挖个坑,后面有时间(福来阁)看看二分法怎么做。