【leetcode】 Merge Intervals
Merge Intervals
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]
.
解题思路: 根据start对区间进行排序,然后依次遍历进行区间合并。
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ bool cmp(const Interval &a, const Interval &b){ return a.start < b.start; } class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { if(intervals.size() == 0) return intervals; sort(intervals.begin(), intervals.end(), cmp); vector<Interval> result; Interval mover = intervals[0]; for(int i = 1; i < intervals.size(); ++i){ if(mover.end < intervals[i].start){ result.push_back(mover); mover = intervals[i]; }else{ mover.end = max(mover.end, intervals[i].end); } } result.push_back(mover); return result; } };