-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathoverlapping_intervals.cpp
54 lines (47 loc) · 1.15 KB
/
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
54
// 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);
arr[index].s = min(arr[index].s, arr[i].s);
}
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 << "] ";
}
int main()
{
Interval arr[] = { {6,8}, {1,9}, {2,4}, {4,7} };
int n = sizeof(arr)/sizeof(arr[0]);
mergeIntervals(arr, n);
return 0;
}