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.
1 public class Solution { 2 public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) { 3 ArrayList<Interval> res = new ArrayList<Interval>(); 4 if(intervals.size()==0){ 5 res.add(newInterval); 6 return res; 7 } 8 for(int i=0;i<intervals.size();i++){ 9 Interval cur = intervals.get(i); 10 if(newInterval.end<cur.start){ 11 res.add(newInterval); 12 for(int j=i;j<intervals.size();j++){ 13 res.add(intervals.get(j)); 14 } 15 return res; 16 } 17 else if(cur.end<newInterval.start){ 18 res.add(cur); 19 } 20 else{ 21 int left = Math.min(newInterval.start,cur.start); 22 int right = Math.max(newInterval.end,cur.end); 23 newInterval.start = left; 24 newInterval.end =right; 25 } 26 } 27 res.add(newInterval); 28 return res; 29 } 30 }