[InterviewBit] Merge Overlapping Intervals

Merge Overlapping Intervals

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
vector<Interval> Solution::merge(vector<Interval> &A) {
sort(begin(A), end(A), [](auto a, auto b) {
return a.start < b.start;
});
vector<Interval> res;
for(auto& a : A) {
if(res.empty() or res.back().end < a.start) res.push_back(a);
else res.back().end = max(res.back().end, a.end);
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/20/PS/interviewbit/merge-overlapping-intervals/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.