区间合并

  • 中国地质大学(武汉)2024 年新生赛(同步赛)- J 题时遇到合并重复区间,遂记录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
vector<vector<double>> merge(vector<vector<double>>& intervals) {
if (intervals.size() == 0) {
return {};
}
sort(intervals.begin(), intervals.end());
vector<vector<double>> merged;
for (decltype(intervals.size()) i = 0; i < intervals.size(); ++i) {
double L = intervals[i][0], R = intervals[i][1];
if (!merged.size() || merged.back()[1] < L) {
merged.push_back({L, R});
} else {
merged.back()[1] = max(merged.back()[1], R);
}
}
return merged;
}

reference

  • 56. 合并区间