19.2.8 [LeetCode 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 considered overlapping.

题意

合并重合的闭区间

题解

 1 bool operator <(const Interval& a, const Interval& b) {
 2     if (a.start == b.start)
 3         return a.end > b.end;
 4     return a.start < b.start;
 5 }
 6 
 7 class Solution {
 8 public:
 9     vector<Interval> merge(vector<Interval>& intervals) {
10         if (intervals.size()<=1)return intervals;
11         set<Interval>q;
12         while (!intervals.empty()) {
13             Interval now = intervals.back();
14             intervals.pop_back();
15             q.insert(now);
16         }
17         auto pre = q.begin();
18         int mm = (*pre).end;
19         for (auto p = q.begin(); p != q.end(); ) {
20             if (p != q.begin() && (*p).start <= (*pre).end) {
21                 mm = max((*p).end, mm);
22                 auto oldp = p;
23                 p++;
24                 q.erase(oldp);
25             }
26             else if (p != q.begin()) {
27                 int star = (*pre).start;
28                 q.erase(pre);
29                 q.insert(Interval(star, mm));
30                 if ((*p).start <= mm) 
31                     pre = q.find(Interval(star, mm));
32                 else {
33                     pre = p;
34                     p++;
35                 }
36                 mm = (*pre).end;
37             }
38             else p++;
39         }
40         if ((*pre).end < mm) {
41             q.insert(Interval((*pre).start, mm));
42             q.erase(pre);
43         }
44         return vector<Interval>(q.begin(),q.end());
45     }
46 };
View Code

猜你喜欢

转载自www.cnblogs.com/yalphait/p/10356600.html
今日推荐