Leetcode: Insert Interval
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].
If output is List:
1 /** 2 * Definition for an interval. 3 * public class Interval { 4 * int start; 5 * int end; 6 * Interval() { start = 0; end = 0; } 7 * Interval(int s, int e) { start = s; end = e; } 8 * } 9 */ 10 public class Solution { 11 public List<Interval> insert(List<Interval> intervals, Interval newInterval) { 12 if (intervals.size() == 0) { 13 intervals.add(newInterval); 14 return intervals; 15 } 16 ArrayList<Interval> res = new ArrayList<Interval>(); 17 int cur = 0; 18 while (cur < intervals.size() && intervals.get(cur).end < newInterval.start) { 19 res.add(intervals.get(cur)); 20 cur++; 21 } 22 while (cur < intervals.size() && intervals.get(cur).start <= newInterval.end) { 23 newInterval.start = Math.min(newInterval.start, intervals.get(cur).start); 24 newInterval.end = Math.max(newInterval.end, intervals.get(cur).end); 25 cur++; 26 } 27 res.add(newInterval); 28 while (cur < intervals.size()) { 29 res.add(intervals.get(cur)); 30 cur++; 31 } 32 return res; 33 } 34 }
If output is array:
1 class Solution { 2 public int[][] insert(int[][] intervals, int[] newInterval) { 3 int i = 0; 4 ArrayList<int[]> list = new ArrayList<int[]>(); 5 while (i < intervals.length && intervals[i][1] < newInterval[0]) { 6 list.add(intervals[i]); 7 i ++; 8 } 9 10 while (i < intervals.length && newInterval[1] >= intervals[i][0]) { 11 newInterval[0] = Math.min(newInterval[0], intervals[i][0]); 12 newInterval[1] = Math.max(newInterval[1], intervals[i][1]); 13 i ++; 14 } 15 16 list.add(newInterval); 17 18 while (i < intervals.length) { 19 list.add(intervals[i]); 20 i ++; 21 } 22 23 int[][] res = new int[list.size()][2]; 24 for (int j = 0; j < list.size(); j ++) { 25 res[j] = list.get(j); 26 } 27 return res; 28 } 29 }
24-27 line can also be
int[][] res = new int[list.size()][2]; res = list.toArray(res); return res;