-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge_Overlapping_Intervals.cpp
More file actions
60 lines (48 loc) · 1.02 KB
/
Copy pathMerge_Overlapping_Intervals.cpp
File metadata and controls
60 lines (48 loc) · 1.02 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
55
56
57
58
59
60
#include <bits/stdc++.h>
using namespace std;
class Interval
{
public:
int start, end;
};
bool compare(Interval i1, Interval i2)
{
return (i1.start < i2.start);
}
void mergeIntervals(Interval a[], int n)
{
if (n <= 0)
return;
sort(a, a + n, compare);
stack<Interval> s;
s.push(a[0]);
for (int i = 1; i < n; i++)
{
Interval current = s.top();
// Now check it with current Interval i.e. a[i].
// IMPORTANT STEP.
if (current.end < a[i].start)
s.push(a[i]);
else if (current.end < a[i].end)
{
current.end = a[i].end;
s.pop();
s.push(current);
}
}
cout << "\n The Merged Intervals are: ";
while (!s.empty())
{
Interval t = s.top();
cout << "[" << t.start << "," << t.end << "] ";
s.pop();
}
return;
}
int main()
{
Interval a[] = {{1, 3}, {2, 4}, {5, 7}, {6, 8}};
int n = sizeof(a) / sizeof(a[0]);
mergeIntervals(a, n);
return 0;
}