『贪心+排序』题解 | #合并区间#
合并区间
http://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
算法
- 思考方式:线段贪心
- 代码实现:排序
- 『我落在你落在的区间,那我们是不是可以合并』
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ bool cmp( Interval a, Interval b ) { if( a.start!=b.start ) { return a.start<b.start; } else { return a.end<b.end; } } class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { int Len=intervals.size(); if( 0==Len || 1==Len ) return intervals; vector<Interval> res; sort( intervals.begin(), intervals.end(), cmp ); Interval Last=intervals[0]; Interval cur; for(int i=0; i<Len; ++i) { Interval cur=intervals[i]; if( cur.start>=Last.start && cur.start<=Last.end ) { //Last的start不变 Last.end= max( Last.end , cur.end ); } else { res.push_back(Last); Last=cur; } } //擦屁股 res.push_back( Last ); return res; } };