-
Notifications
You must be signed in to change notification settings - Fork 232
/
Copy pathMerge_Overlapping_Intervals.cpp
53 lines (45 loc) · 1.2 KB
/
Merge_Overlapping_Intervals.cpp
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
// C++ program to merge overlapping Intervals in
// O(n Log n) time and O(1) extra space.
#include <bits/stdc++.h>
using namespace std;
// An Interval
struct Interval {
int s, e;
};
// Function used in sort
bool mycomp(Interval a, Interval b) { return a.s < b.s; }
void mergeIntervals(Interval arr[], int n)
{
// Sort Intervals in increasing order of
// start time
sort(arr, arr + n, mycomp);
int index = 0; // Stores index of last element
// in output array (modified arr[])
// Traverse all input Intervals
for (int i = 1; i < n; i++) {
// If this is not first Interval and overlaps
// with the previous one
if (arr[index].e >= arr[i].s) {
// Merge previous and current Intervals
arr[index].e = max(arr[index].e, arr[i].e);
}
else {
index++;
arr[index] = arr[i];
}
}
// Now arr[0..index-1] stores the merged Intervals
cout << "\n The Merged Intervals are: ";
for (int i = 0; i <= index; i++)
cout << "[" << arr[i].s << ", " << arr[i].e << "] ";
}
// Driver program
int main()
{
Interval arr[]
= { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } };
int n = sizeof(arr) / sizeof(arr[0]);
mergeIntervals(arr, n);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)