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]
.
O(n)
独立方法1:
关键是要1.根据铰接窗口延展newInterval左右一点点 2.把延展后的newInterval插在正确的位置。
1.遍历元素,同时做两件事情 a.非铰接的就直接放入结果,同时用一个指针记录着该放前面的放多少个了来指示最后把newInterval插在上面位置。b.铰接的来试着延展newInterval
2.插入newInterval。
依赖上题方法2:
首先先按照当前newInterval的start找到在原列表里按顺序应该插入的位置,直接插进去,然后再做一次上面的merge。(因为省去了sort,所以时间复杂度还是O(n))
1.实现 elegant版
/** * 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) { if (newInterval == null) { return intervals; } List<Interval> result = new ArrayList<>(); if (intervals == null) { result.add(newInterval); return result; } int insertIdx = 0; for (Interval interval : intervals) { if (interval.end < newInterval.start) { result.add(interval); insertIdx++; } else if (interval.start > newInterval.end) { result.add(interval); } else { newInterval.start = Math.min(newInterval.start, interval.start); newInterval.end = Math.max(newInterval.end, interval.end); } } result.add(insertIdx, newInterval); return result; } }
2.实现ugly版的,遍历了两次,第一次专门拓展,第二次专门加组
/** * 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) { if (newInterval == null) { return intervals; } List<Interval> result = new ArrayList<>(); if (intervals == null || intervals.size() == 0) { result.add(newInterval); return result; } for (int i = 0; i < intervals.size(); i++) { if (intervals.get(i).end >= newInterval.start) { newInterval.start = Math.min(newInterval.start, intervals.get(i).start); } if (intervals.get(i).start <= newInterval.end) { newInterval.end = Math.max(newInterval.end, intervals.get(i).end); } } int i; for (i = 0; i < intervals.size(); i++) { if (intervals.get(i). end < newInterval.start) { result.add(intervals.get(i)); } else { break; } } result.add(newInterval); for ( ; i < intervals.size(); i++) { if (intervals.get(i).start <= newInterval.end) { continue; } else { result.add(intervals.get(i)); } } return result; } }