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

Merge Intervals

时间:2015-07-14 22:36:08      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:

代码:

 1 #include<iostream>
 2 #include<vector>
 3 #include<algorithm>
 4 
 5 using namespace std;
 6 
 7 struct Interval {
 8     int start;
 9     int end;
10     Interval() : start(0), end(0) {}
11     Interval(int s, int e) : start(s), end(e) {}
12 };
13 
14 bool compare(Interval &a, Interval &b)
15 {
16     return a.start < b.start;
17 }
18 
19 vector<Interval> merge(vector<Interval>& intervals) 
20 {
21     vector<Interval> result;
22     sort(intervals.begin(), intervals.end(), compare);
23     for (int i = 0; i < intervals.size()-1; i++)
24     {
25         if ((i+1!=intervals.size()-1)&&intervals[i].end >= intervals[i + 1].start)
26         {
27             intervals[i].end = intervals[i + 1].end;
28         }
29         else
30         {
31             result.push_back(intervals[i]);
32         }
33     }
34     return result;
35 }
36 
37 
38 int main()
39 {
40     Interval I1(1,3);
41     Interval I2(2,6);
42     Interval I3(8, 10);
43     Interval I4(15,18);
44     vector<Interval> itervals;
45     itervals.push_back(I1);
46     itervals.push_back(I2);
47     itervals.push_back(I3);
48     itervals.push_back(I4);
49 
50     vector<Interval> result = merge(itervals);
51     for (int i = 0; i < result.size(); i++)
52     {
53         cout << result[i].start << "    " << result[i].end << endl;
54     }
55 }

 

Merge Intervals

标签:

原文地址:http://www.cnblogs.com/chaiwentao/p/4646651.html

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