本文主要是介绍[leetcode刷题系列]Merge Intervals,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
贪心排序一下, 然后不断的merge就好了
/*** 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(const Interval& a, const Interval& b){return a.end < b.end;
}
class Solution {Interval merge(Interval& a, Interval &b){int st = min(a.start, b.start);int en = max(a.end, b.end);return Interval(st, en);}
public:vector<Interval> merge(vector<Interval> &intervals) {// Start typing your C/C++ solution below// DO NOT write int main() functionstd::sort(intervals.begin(), intervals.end(), cmp);vector<Interval> ret;for(int i = 0; i < intervals.size(); ++ i){ret.push_back(intervals[i]);while(ret.size() > 1){if(ret[ret.size() - 1].start <= ret[ret.size() - 2].end){Interval ii = merge(ret[ret.size() - 1], ret[ret.size() - 2]);ret.pop_back();ret.pop_back();ret.push_back(ii);}else break;}}return ret;}
};
这篇关于[leetcode刷题系列]Merge Intervals的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!