Monday, December 29, 2014

Insert Interval (LeetCode Array)

Question:  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].

Idea: Consider it as copying the input list and the newInterval to a new list with merge during the process. First initial an empty list<Interval> as the result. Then we copy each interval "i" in the input list<Interval> to the result. During the copying, we compare each "i" with the newInterval,
There are three cases:
1) the newInterval is on i's left, we need to remember i's index to insert newInterval on the left of i;
2) the newInterval is on i's right, we need to remember i's index to insert newInterval on the right of i;
3) the newInterval overlaps with i, then we merge newInterval and i and remember the updated newInterval should be placed at the index of i.

Time: O(n) Space: O(n)

Code: 
 public class Solution {  
   public List<Interval> insert(List<Interval> intervals, Interval newInterval) {  
     int pos=0;  
     List<Interval> result=new ArrayList<Interval>();  
     for(Interval i:intervals)  
     {  
       if(i.end<newInterval.start)  
       {  
         result.add(i);  
         pos+=1;  
       }  
       else if(i.start>newInterval.end)  
         result.add(i);  
       else  
       {  
         newInterval.start=Math.min(newInterval.start,i.start);  
         newInterval.end=Math.max(newInterval.end,i.end);  
       }  
     }  
     result.add(pos,newInterval);  
     return result;  
   }  
 }  




No comments:

Post a Comment