Wednesday, January 21, 2015

Merge Intervals (LeetCode Sort)

Question: Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

Idea: First sort the intervals according to their start point. Then use a variable to cache the previous interval and scan the list from left to right (ascending order). If the previous interval does not overlap with the current interval, append previous interval to the result, otherwise merge the previous interval and the current interval and store the new interval in the variable previous. When the loop is done, do not forget the last interval is not appended to result, since there is no current interval now.

Time: O(nlgn) Space: O(1)

Code:
 public class Solution {  
   public Comparator<Interval> comp=new Comparator<Interval>()  
   {  
     public int compare(Interval i1, Interval i2)  
     {  
       if(i1==null)  
         return 1;  
       else if(i2==null)  
         return -1;  
       else  
         return i1.start-i2.start;  
     }  
   };  
   public List<Interval> merge(List<Interval> intervals) {  
     if(intervals.size()<=1)  
       return intervals;  
     List<Interval> result=new ArrayList<Interval>();  
     Collections.sort(intervals,comp);  
     Interval pre=intervals.get(0);  
     for(int i=1;i<intervals.size();i++)  
     {  
       if(pre.end<intervals.get(i).start)  
       {  
         result.add(pre);  
         pre=intervals.get(i);  
       }  
       else  
       {  
         pre.start=Math.min(pre.start,intervals.get(i).start);  
         pre.end=Math.max(pre.end,intervals.get(i).end);  
       }  
     }  
     result.add(pre);  
     return result;  
   }  
 }  

No comments:

Post a Comment