题解 | #合并区间#
合并区间
https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
我算是明白了,手搓快排是过不了的,唯有标准库sort
/**
* struct Interval {
* int start;
* int end;
* Interval(int s, int e) : start(start), end(e) {}
* };
*/
static const auto io_sync_off = []() {
std::ios::sync_with_stdio(false);//关闭输入输出
std::cin.tie(nullptr);//取消两个stream绑定
std::cout.tie(nullptr);//取消cin 和 cout之间的绑定,加快执行效率
return nullptr;
}
();
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param intervals Interval类vector
* @return Interval类vector
*/
vector<Interval> merge(vector<Interval>& intervals) {
if (intervals.size() < 2) {
return intervals;
}
// 使用 std::sort 进行排序
std::sort(intervals.begin(), intervals.end(), [](Interval& a, Interval& b){
return a.start < b.start;
});
vector<Interval> res;
Interval ptr = intervals[0];
for (int i = 1; i < intervals.size(); ++i) {
if (intervals[i].start <= ptr.end) {
ptr.end = max(ptr.end, intervals[i].end);
} else {
res.push_back(ptr);
ptr = intervals[i];
}
}
res.push_back(ptr);
return res;
}
};


查看1道真题和解析