[Leetcode]56. Merge Intervals
阿新 • • 發佈:2018-11-19
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considerred overlapping.
思路很簡單,就是首先排序,這裡為了練習快排,所以自己手寫了以個排序。
針對intervals進行排序,然後進行類似於mapreduce中的reduce工作一樣,進行歸併,得到結果,具體看程式碼。
const int x=[](){ std::ios::sync_with_stdio(false); std::cin.tie(nullptr); return 0; }(); class Solution { public: void swap(Interval &a, Interval &b){ Interval temp=a; a=b; b=temp; } void mysqrt(vector<Interval>& intervals, int left, int right){ if(left>=right) return; int i=left-1; int j=right; for(int k=left;k<right;k++){ if(intervals[k].start<intervals[right].start){ i++; swap(intervals[k],intervals[i]); } } i++; swap(intervals[i],intervals[right]); mysqrt(intervals,left,i-1); mysqrt(intervals,i+1,right); } vector<Interval> merge(vector<Interval>& intervals) { if(intervals.empty()) return intervals; mysqrt(intervals,0,intervals.size()-1); vector<Interval> ans; Interval cur=intervals[0]; for(int i = 1; i < intervals.size(); i++){ if(intervals[i].start <= cur.end){ cur.end=intervals[i].end > cur.end? intervals[i].end : cur.end; }else{ ans.push_back(cur); cur=intervals[i]; } } ans.push_back(cur); return ans; } };