【leetcode】Merge Intervals(hard)
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]
.
思路:开始想用线段树,后来想想这个不是动态变化的没必要。
按区间的第一个值从小到大排序,然后跳过后面被覆盖的区间来找。
sort折腾了好久,开始搞不定只好自己写了一个归并排序。现在代码里的sort是可用的。
class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { //mysort(intervals, 0, intervals.size() - 1); sort(intervals.begin(), intervals.end(), comp); vector<Interval> ans; Interval tmp; for(int i = 0; i < intervals.size(); i++) //找每个连续的区间 { tmp.start = intervals[i].start; int curmaxend = intervals[i].end; //注意这里要记录当前区间最大的那个值 因为有可能[1,100],[2,3]这样前面最大值比后面大 while(i + 1 < intervals.size() && curmaxend >= intervals[i + 1].start) { curmaxend = (intervals[i + 1].end > curmaxend) ? intervals[i + 1].end : curmaxend; i++; } tmp.end = curmaxend; ans.push_back(tmp); } return ans; } void mysort(vector<Interval> &intervals, int s, int e) { if(s >= e) return; int m = (s + e) / 2; mysort(intervals, s, m); mysort(intervals, m + 1, e); merge(intervals, s, m, e); } void merge(vector<Interval> &intervals, int s, int m, int e) { vector<Interval> left(intervals.begin() + s, intervals.begin() + m + 1); vector<Interval> right(intervals.begin() + m + 1, intervals.begin() + e + 1); int l = 0, r = 0, n = s; while(l < left.size() && r < right.size()) { intervals[n++] = (left[l].start < right[r].start) ? left[l++] : right[r++]; } while(l < left.size()) { intervals[n++] = left[l++]; } while(r < right.size()) { intervals[n++] = right[r++]; } } static bool comp(const Interval& a, const Interval& b){ return a.start < b.start; } };