首页 > 其他 > 详细

Merge Intervals

时间:2014-03-23 21:30:40      阅读:391      评论:0      收藏:0      [点我收藏+]

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
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
struct cmp{
    bool operator()(Interval  a,Interval b){
        return a.start < b.start ;
         
    
} comp;
class Solution {
public:
    vector<Interval> merge(vector<Interval> &intervals) {
        sort(intervals.begin(),intervals.end(),comp);
        int size = intervals.size();
        vector<Interval> re;
        if(intervals.size()==0)return re;
        Interval temp;
        int flag = 0;
        for(int i = 0 ; i  < size ;i++)
        {
            if(intervals[i].start >temp.end || flag ==0)
            {
                if(flag ==0)
                {
                    flag =1;
                    temp.start = intervals[i].start;
                    temp.end = intervals[i].end;
                }
                else
                {
                    re.push_back(temp);
                    temp.start =intervals[i].start;
                    temp.end =intervals[i].end;
                }
            }
            else if(intervals[i].start <= temp.end)
            {
                if(temp.end < intervals[i].end)temp.end = intervals[i].end;
            }
        }
        re.push_back(temp);
        return re;
    }
};

  

Merge Intervals,布布扣,bubuko.com

Merge Intervals

原文:http://www.cnblogs.com/pengyu2003/p/3619190.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!