57. Insert Interval - Hard
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]
.
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
3 cases + edge case at the end
1. if newInterval.start > curInterval.end (or newInterval is null)
-> curInterval is valid, insert to list, and leave newInterval to compare with next interval
2. if newInterval.end < curInterval.start
-> both valid, add them to list, and set newInterval to be null, which means has been inserted already
3. other condition, overlap, merge newInterval and curInterval to be a larger interval
time = O(n), space = O(1)
class Solution { public int[][] insert(int[][] intervals, int[] newInterval) { if(intervals.length == 0) { return new int[][] {newInterval}; } List<int[]> list = new ArrayList<>(); for(int i = 0; i < intervals.length; i++) { // // non-overlap, current interval valid, leave newInterval to compare with next interval if(newInterval == null || newInterval[0] > intervals[i][1]) { list.add(intervals[i]); } else if(newInterval[1] < intervals[i][0]) { // non-overlap, both valid list.add(newInterval); list.add(intervals[i]); newInterval = null; // newInterval inserted, reset to null } else { newInterval[0] = Math.min(newInterval[0], intervals[i][0]); newInterval[1] = Math.max(newInterval[1], intervals[i][1]); } } if(newInterval != null) { // if newInterval haven't been inserted after traversal, insert at the end list.add(newInterval); } int[][] res = new int[list.size()][2]; for(int i = 0; i < list.size(); i++) { res[i] = list.get(i); } return res; } }