排序
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { sort(intervals.begin(), intervals.end(), [](const Interval& a, const Interval& b){ if(a.start != b.start) return a.start < b.start; return a.end < b.end; }); int n = intervals.size(); if(n == 0) return {}; vector<Interval> res; Interval inv(intervals[0].start, intervals[0].end); for(int i = 1; i < n; i ++){ Interval itv = intervals[i]; if(itv.start > inv.end){ res.push_back(inv); inv.start = itv.start; inv.end = itv.end; }else{ inv.start = min(inv.start, itv.start); inv.end = max(inv.end, itv.end); } } res.push_back(inv); return res; } };