/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
bool isLessThan(const Interval& l1, const Interval& l2)
{
return l1.start <= l2.start;
}
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(intervals.begin(), intervals.end(), isLessThan);
Interval* temp = NULL;
vector<Interval> res;
for (int i = 0; i < intervals.size(); ++i)
{
Interval cur = intervals[i];
if (temp == NULL || temp->end < cur.start)
{
res.push_back(cur);
temp = &res.back();
}
else if (cur.end > temp->end)
temp->end = cur.end;
}
return res;
}
};[Leetcode] Merge Intervals
最新推荐文章于 2021-12-01 20:25:26 发布
本文介绍了一种区间合并算法的实现方式,通过定义区间结构体并利用比较函数进行排序,然后遍历区间列表完成合并操作。该算法适用于需要处理一系列不重叠区间的应用场景。
298

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



