1. 程式人生 > >[LeetCode] Merge Intervals

[LeetCode] Merge Intervals

err aps ack script out pull 混合 cmp example

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.
混合包含的區間 思路: 0. 需要將給定數組按照start的升序排序,當start相同時,按end升序排序。 1. 需要混合的區間包含如下情況   1. 如果start相同,若後一個元素的end大於前一個元素end,則融合   2. 如果start不同,若後一個元素的end大於前一個元素end,則融合 2. 不需要融合的情況   1. 前一個元素end小於後一個元素的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) {}
 * };
 
*/ class Solution { public: static bool cmp(const Interval& a, const Interval& b) { return a.start < b.start || (a.start == b.start && a.end < b.end); } vector<Interval> merge(vector<Interval>& intervals) { sort(intervals.begin(), intervals.end(), cmp); vector
<Interval> res; for (int i = 0; i < intervals.size(); ++i) { if (i == 0 || intervals[i].start > res.back().end) res.push_back(intervals[i]); else if (intervals[i].end > res.back().end) res.back().end = intervals[i].end; } return res; } };

[LeetCode] Merge Intervals