题解 | #合并区间#
合并区间
https://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) {}
* };
*/
#include <vector>
class Solution {
public:
//定义排序规则,按照区间的左端点排序
// static bool cmp(const Interval &a,const Interval &b){
// return (a.start<b.start);
// }
vector<Interval> merge(vector<Interval> &intervals) {
sort(intervals.begin(), intervals.end(),[&](Interval & a, Interval & b){
return a.start < b.start;
});
vector<Interval> res;
int st = -1, end = -1;
for(auto num : intervals){
if(end < num.start){
if(st != -1) res.push_back(Interval(st, end));
st = num.start, end = num.end;
} else {
end = max(num.end, end);
}
}
if(st != -1)
res.push_back(Interval(st,end));
return res;
}
};
深信服公司福利 832人发布

