56. Merge Intervals
问题描述:
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.
解题思路:
现将给出的数组按照start的大小由小到大排序。
将第一个压入返回数组。
比较数组中最后一个Interval的end与当前interval的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) {} * }; */ struct cmp{ bool operator() (const Interval &i1, const Interval &i2){ return i1.start < i2.start; } }; class Solution { public: vector<Interval> merge(vector<Interval>& intervals) { vector<Interval> ret; if(intervals.size() < 2) return intervals; sort(intervals.begin(), intervals.end(), cmp() ); ret.push_back(intervals[0]); for(int i = 1; i < intervals.size(); i++){ if(intervals[i].start > ret.back().end){ ret.push_back(intervals[i]); }else{ ret.back().end = max(ret.back().end, intervals[i].end); } } return ret; } };