56. Merge Intervals

Proble statement:

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

Solution:

First, we should sort the intervals by the value of start of each element. Initialize a start and end value as the value of first element in the array.

Second, loop the intervals array from second element to see if current end value is greater or equal to the next start value

  • if yes, they could been merged, we should update the end value, we choose the bigger one betwee two intervals.
  • otherwise, this is a new interval, but we should push back last interval and initialize the start and end value of

return the interval array

 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 class Solution {
11 public:
12     vector<Interval> merge(vector<Interval>& intervals) {
13         vector<Interval> merge_list;
14         if(intervals.empty()){
15             return merge_list;
16         }
17         // sort the intervals by the value of start of each element
18         sort(intervals.begin(), intervals.end(), [](const Interval& lhs, const Interval& rhs){ 
19             return lhs.start < rhs.start;
20         });
21         
22         // initialize the merge_interval
23         Interval merge_interval;
24         merge_interval.start = intervals[0].start;
25         merge_interval.end = intervals[0].end;
26         
27         for(vector<int>::size_type ix = 1; ix < intervals.size(); ix++){
28             // current interval could been merged with previous interval
29             if(merge_interval.end >= intervals[ix].start){
30                 merge_interval.end = merge_interval.end > intervals[ix].end ? merge_interval.end : intervals[ix].end;
31             } else {
32                 // current interval could not been merged with previous interval
33                 // push back the interval
34                 merge_list.push_back(merge_interval);
35                 // reinitialize the start and end value of merge interval
36                 merge_interval.start = intervals[ix].start;
37                 merge_interval.end = intervals[ix].end;
38             }
39         }
40         // push back the last element
41         merge_list.push_back(merge_interval);
42         return merge_list;
43     }
44 };

 

posted @ 2017-02-06 03:43  蓝色地中海  阅读(142)  评论(0编辑  收藏  举报