题解 | #合并区间#
合并区间
https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
/** * struct Interval { * int start; * int end; * Interval(int s, int e) : start(start), end(e) {} * }; */ #include <iterator> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param intervals Interval类vector * @return Interval类vector */ void QuickSort(vector<Interval> &arr,int l,int r) { if(!arr.empty()) { int mid = Split(arr,l,r); QuickSort(arr, l, mid-1); QuickSort(arr, mid+1, r); } } int Split(vector<Interval> &arr,int l,int r) { Interval pivot = arr[l]; while(l < r) { while(arr[r].start > pivot.start && l<r) { r--; } if(l < r) { swap(arr[l++],arr[r]); } while(arr[l].start < pivot.start && l<r) { l++; } if(l < r) { swap(arr[l],arr[r--]); } } return l; } static bool cmp(Interval& a,Interval& b) { return a.start < b.start; } vector<Interval> merge(vector<Interval>& intervals) { // write code here if(intervals.size() == 0) return intervals; //QuickSort(intervals,0,intervals.size()-1); sort(intervals.begin(),intervals.end(),cmp); vector<Interval> ans; ans.push_back(intervals.front()); for(int i = 1;i<intervals.size();i++) { if(intervals[i].start <= ans.back().end) { ans.back().end = max(intervals[i].end,ans.back().end); } else { ans.push_back(intervals[i]); } } return ans; } };