欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢
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) {} * }; */ //方法:先sort,然后再考虑情况合并。复杂度:O(nlogn) class Solution { public: struct compare { bool operator()( const Interval& a , const Interval& b) const { if( a.start==b.start) return a.end < b.end; else return a.start < b.start; } }; vector<Interval> merge(vector<Interval> &intervals) { if(intervals.size()==0) return vector<Interval>(); sort(intervals.begin() , intervals.end() , compare()); vector<Interval> ans; Interval temp; temp = intervals[0]; for(int i=1; i<intervals.size(); i++) { if(intervals[i].start <= temp.end ) temp.end = max(intervals[i].end , temp.end); else { ans.push_back(temp); temp = intervals[i]; } } ans.push_back(temp); return ans; } };
时间: 2024-10-07 00:45:41