首页 > 代码库 > Merge Intervals

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

思路:先对输入数据按start递增排序,然后再进行合并。

 1 bool comp( Interval interval1, Interval interval2 ) { 2     return interval1.start < interval2.start; 3 } 4  5 class Solution { 6 public: 7     vector<Interval> merge( vector<Interval> &intervals ) { 8         sort( intervals.begin(), intervals.end(), comp ); 9         vector<Interval> ret;10         for( auto iter = intervals.begin(); iter != intervals.end(); ++iter ) {11             if( ret.empty() || ret.back().end < iter->start ) {12                 ret.push_back( *iter );13             } else {14                 ret.back().end = max( ret.back().end, iter->end );15             }16         }17         return ret;18     }19 };

 

Merge Intervals