您的位置:首页 > 编程语言 > C语言/C++

leetcode_c++:Merge_Intervals(056)

2016-05-31 22:44 330 查看

题目

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

算法

复杂度:O(nm)

#include<iostream>
#include<vector>
#include <algorithm>

using namespace std;

const int N=0;

struct Interval {
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
};

bool isLess(const Interval &a, const Interval &b){
return a.start<b.start;
}

class Solution{
public:
vector<Interval> merge(vector<Interval> &intervals){
int nSize=intervals.size();
vector<Interval>  result;
if(nSize==0)
return result;

sort(intervals.begin(),intervals.end(),isLess);
Interval val=intervals[0];
Interval next;
for(int i=1;i<nSize;++i){
next=intervals[i];
if(next.start>val.end){
result.push_back(val);
val=next;

}else{
val.end=val.end>next.end? val.end:next.end;
}

}

result.push_back(val);
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: