将intervals的元素按照start从小到大的顺序排序,并将有重叠区域的相邻元素融合;
/**
* 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:
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
vector<Interval> res;
intervals.push_back(newInterval);
sort(intervals.begin(),intervals.end(),cmp); //sort the intervals elements according to the start time
int num=0;
res.push_back(intervals[num]);
for(int i =1;i<intervals.size();i++)
{
if(res[num].end>=intervals[i].start)
{
if(res[num].end<intervals[i].end)
res[num].end=intervals[i].end;
}
else
{
num++;
res.push_back(intervals[i]);
}
}
return res;
}
bool static cmp(Interval &A,Interval &B)
{
return A.start<B.start;
}
};
本文介绍了一种区间合并算法,该算法首先将输入的区间按起始时间排序,然后遍历每个区间,将重叠的区间进行合并。通过这种方法,可以有效地减少处理连续区间问题时的数据冗余。
412

被折叠的 条评论
为什么被折叠?



