Saturday, September 20, 2014

LeetCode: Merge Intervals

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


 /**  
  * Definition for an interval.  
  * struct Interval {  
  *   int start;  
  *   int end;  
  *   Interval() : start(0), end(0) {}  
  *   Interval(int s, int e) : start(s), end(e) {}  
  * };  
  */  
   
   static bool compare(Interval x, Interval y)  
   {  
     return (x.start < y.start);  
   }  
   
   vector<Interval> merge(vector<Interval> &intervals) {  
     sort(intervals.begin(), intervals.end(), compare);  
   
     int n = intervals.size();  
     vector<Interval> res;  
   
     for (int i = 0; i< n; i++)  
     {  
       int j = i;  
       int greatest = intervals[i].end;  
       while (j<n-1 && intervals[j+1].start <= greatest){  
         j++;  
         if(intervals[j].end > greatest)greatest = intervals[j].end;  
       }  
       if(j == i)  
       {  
         res.push_back(intervals[i]);  
       }  
       else  
       {  
         Interval x(intervals[i].start, greatest);  
         res.push_back(x);  
         i = j;  
       }  
     }  
     return res;  
   }  

No comments:

Post a Comment