[LeetCode] Merge Intervals

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

 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 comp(const Interval &lhs, const Interval &rhs)
12 {
13     return lhs.start < rhs.start;
14 }
15 
16 class Solution {
17 private:
18     vector<Interval> ret;
19 public:
20     vector<Interval> merge(vector<Interval> &intervals) {
21         // Start typing your C/C++ solution below
22         // DO NOT write int main() function
23         ret.clear();
24         
25         sort(intervals.begin(), intervals.end(), comp);
26         for(int i = 0; i < intervals.size(); i++)
27             if (ret.size() == 0)
28                 ret.push_back(intervals[i]);
29             else
30             {
31                 int size = ret.size();
32                 if (ret[size-1].start <= intervals[i].start && intervals[i].start <= ret[size-1].end)
33                     ret[size-1].end = max(ret[size-1].end, intervals[i].end);
34                 else
35                     ret.push_back(intervals[i]);
36             }
37             
38             
39         return ret;
40     }
41 };
posted @ 2012-11-25 11:53  chkkch  阅读(2124)  评论(0编辑  收藏  举报