[Leetcode 84] 56 Merge Intervals

Problem:

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].

Analysis:

First sort the vector according to the start time of each interval. Then scan through the vector, if the current interval's start time is between the former interval's strart and end time, we need to merge them. The newly merged interval's start is the former interval's start, but the end should be the max{current.end, former.end}.

To speed up this process, use an extra result vector to store the final result rather than using vector.erase method on original method.

Code:

 1 /**
 2  * Definition for an interval.
 3  * struct Interval {
 4  *     int start;
 5  *     int end;
 6  *     Interval() : start(0), end(0) {}
 7  *     Interval(int s, int e) : start(s), end(e) {}
 8  * };
 9  */
10  
11 bool cmpA(const Interval& a, const Interval& b)
12 {
13     return a.start < b.start;
14 }
15 
16 class Solution {
17 public:
18     vector<Interval> merge(vector<Interval> &intervals) {
19         // Start typing your C/C++ solution below
20         // DO NOT write int main() 
21         vector<Interval> res;
22         sort(intervals.begin(), intervals.end(), cmpA);
23 
24         Interval tmp = intervals[0];
25         for (int i=1; i<intervals.size(); i++) {
26             if (tmp.start <= intervals[i].start &&
27                 tmp.end >= intervals[i].start) {
28                     tmp.end = max(intervals[i].end, tmp.end);
29             }
30             else {
31                 res.push_back(tmp);
32                 tmp = intervals[i];
33             }
34         }
35 
36         return res;
37     }
38     
39     int max(int a, int b) {
40         return (a>b)? a : b;
41     }
42 };
View Code
原文地址:https://www.cnblogs.com/freeneng/p/3210450.html