-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunion_interval.cpp
More file actions
36 lines (30 loc) · 882 Bytes
/
union_interval.cpp
File metadata and controls
36 lines (30 loc) · 882 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include "union_interval.h"
#include <algorithm>
auto UnionInterval::UnionOfIntervals(std::vector<std::pair<int, int>>& intervals)
-> std::vector<std::pair<int, int>>
{
// if array is empty
if (intervals.empty())
{
return {};
}
// sort intervals by start time
std::ranges::sort(intervals, [](const std::pair<int, int>& a, const std::pair<int, int>& b) {
return a.first < b.first;
});
std::vector<std::pair<int, int>> result;
result.push_back(intervals[0]);
for (const auto& interval : intervals)
{
// if current interval overlaps with the previous
if (interval.first <= result.back().second)
{
result.back().second = std::max(result.back().second, interval.second);
}
else
{
result.push_back(interval);
}
}
return result;
}