LeetCode-Merge Intervals
2018-09-22 本文已影响0人
圣地亚哥_SVIP
题目要求:
给定一个interval的集合,合并重合的部分:
如:[[1,4],[2,6]] -> [[1,6]]
解题要点:
- 先对interval序列进行排序,排序的依据是interval.end;
- 从序列尾部依次往头合并
合并的原则:
当期interval
待合并的Interval: ml
判断interval ml能否合并,如能合并,将合并后生成的新的interval作为当前Interval,如不能合并,说明当前interval已经不能与序列中任何一个进行合并(不能合并说明当前interval.start>ml.end,序列是有序序列,说明当前interval不能与序列中任何一个Interval合并),当前的interval可以加入结果集。
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
auto merge_two(vector<Interval>& intervals,Interval& interval,int index,bool& merged){
auto ml = intervals[index];
if (ml.end<interval.start){
merged = false;
ml = interval;
}else{
merged = true;
ml.start = ml.start>interval.start? interval.start:ml.start;
ml.end = interval.end;
}
return ml;
}
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval> res;
if (intervals.size()<=1){
res = intervals;
return res;
}
sort(intervals.begin(),intervals.end(),[](const auto& r,const auto& l){return r.end < l.end;});
auto interval = intervals[intervals.size()-1];
int index = intervals.size()-2;
bool merged = false;
while(index >= 0){
auto tmp = merge_two(intervals,interval,index,merged);
if (merged){
interval = tmp;
}else{
res.push_back(tmp);
interval = intervals[index];
}
index--;
merged=false;
}
res.push_back(interval);
std::reverse(res.begin(),res.end());
return res;
}
};