码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Merge Intervals

时间:2015-01-07 23:24:02      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

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 class Solution {
11 public:
12     vector<Interval> merge(vector<Interval> &intervals) {
13         vector<Interval> result;
14         if(intervals.empty()) return result;
15        
16         sort(intervals.begin(),intervals.end(),cmp);
17        
18         int start=intervals[0].start;
19         int end=intervals[0].end;
20        
21         for(int i=1;i<intervals.size();i++)
22         {
23             if(intervals[i].start<=end)
24             {
25                 //注意[1,4],[2,3]的情况
26                 end=end<intervals[i].end?intervals[i].end:end;
27             }
28             else
29             {
30                 result.push_back(Interval(start,end));
31                 start=intervals[i].start;
32                 end=intervals[i].end;
33             }
34         }
35  
36         result.push_back(Interval(start,end));
37         return result;
38     }
39    
40     static int cmp(const Interval &a,const Interval &b)
41     {
42         if(a.start<b.start) return 1;
43         else if(a.start>b.start) return 0;
44         else return a.end<b.end;
45     }
46 };

 

【leetcode】Merge Intervals

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4209522.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!