在解决这个问题的时候,我的思路是: Interval的形式为(start,end)
1)按照Interval的第一个数值start进行排序,得到排序后数组
2)现在对排序后的数组进行合并操作,我们想象有一条直线,所有的间隔都是线段
考虑一个间隔I1=(s1,e1)和它的后一个间隔I2=(s2,e2),因为已经排好序,所以s1<s2
当e1 < s2的时候,I1与I2不重合,根据有序性可知I2之后的间隔也与I1不重合,所以I1为目标数组中一个成员
当e1 > s2的时候,两者可以合并为新间隔(s1,maxend),maxend = max(e1,e2),再进行重复(2),考虑新间隔与后续间隔的合并
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL){}
};
struct Interval{
int start;
int end;
Interval():start(0),end(0){}
Interval(int s, int e):start(s),end(e){}
};
class Solution{
public:
vector<Interval> merge(vector<Interval>& intervals){
int index = 0;
int len = intervals.size();
vector<Interval> sortedintervals; //排序后的间隔数组
vector<Interval> res; //返回的间隔数组
for(int k = 0; k < len; ++k ){
index = 0;
for(int i = 0; i < intervals.size();++i){
if(intervals[i].start <= intervals[index].start){
index = i;
}
}
sortedintervals.push_back(intervals[index]);
cout << intervals[index].start << "," << intervals[index].end << endl;
intervals.erase(intervals.begin()+index);
}
int i = 0;
while(i < sortedintervals.size()){
int si = i;
int newend = sortedintervals[si].end;
while(newend >= sortedintervals[i+1].start && i < sortedintervals.size()-1){
if(newend < sortedintervals[i+1].end)
newend = sortedintervals[i+1].end;
i++;
}
res.push_back(Interval(sortedintervals[si].start,newend));
i = i+1;
}
return res;
}
};
int main(){
vector<Interval> intervals,res;
intervals.push_back(Interval(1,4));
intervals.push_back(Interval(0,2));
intervals.push_back(Interval(3,5));
Solution* s = new Solution();
res = s->merge(intervals);
for(int i = 0; i< res.size();++i){
cout<< res[i].start << "," << res[i].end << endl;
}
return 0;
}