-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge_overlapping_intervals.cpp
More file actions
39 lines (39 loc) · 1.11 KB
/
Merge_overlapping_intervals.cpp
File metadata and controls
39 lines (39 loc) · 1.11 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
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
bool compare(Interval x, Interval y){
return (x.start < y.start);
}
vector<Interval> Solution::merge(vector<Interval> &intervals) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
sort(intervals.begin(),intervals.end(),compare);
int n = intervals.size(),i,j;
if (n==1)
return intervals;
vector <Interval> res;
i = 0;
j = 1;
res.push_back(intervals[0]);
while (j<n){
if (res[i].end>=intervals[j].start){
res[i].start = min(res[i].start,intervals[j].start);
res[i].end = max(res[i].end,intervals[j].end);
j++;
}
else{
res.push_back(intervals[j]);
i++;
j++;
}
}
return res;
}