-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunion_interval.h
More file actions
54 lines (45 loc) · 1.36 KB
/
Copy pathunion_interval.h
File metadata and controls
54 lines (45 loc) · 1.36 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#ifndef CPP_ALGORITHM_UNION_INTERVAL_H
#define CPP_ALGORITHM_UNION_INTERVAL_H
#include <algorithm>
#include <vector>
namespace UnionInterval
{
/**
* \brief Union of intervals
* \details Given a set of intervals, find the union of all intervals.
* \param intervals start and end pairs of intervals
* \return union of intervals
*/
std::vector<std::pair<int, int>> UnionOfIntervals(
std::vector<std::pair<int, int>>& intervals);
}
// ----------------------------------------------------------------------------
inline std::vector<std::pair<int, int>> UnionInterval::UnionOfIntervals(
std::vector<std::pair<int, int>>& intervals)
{
// 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;
}
#endif