[InterviewBit] Merge Intervals

Merge Intervals

  • Time :
  • Space :
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
/**
* 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::insert(vector<Interval> &intervals, Interval newInterval) {
vector<Interval> res;
bool fl = false;
int ma = INT_MIN;
for(auto& i : intervals) {
if(!fl) {
if(newInterval.start <= i.start) {
if(!res.empty() and res.back().end >= newInterval.start) {
res.back().end = max(res.back().end, newInterval.end);
} else res.push_back(newInterval);
fl = true;
}
if(!res.empty() and res.back().end >= i.start) {
res.back().end = max(res.back().end, i.end);
} else res.push_back(i);
} else {
if(res.back().end >= i.start) {
res.back().end = max(res.back().end, i.end);
} else res.push_back(i);
}
if(!fl and res.back().end >= newInterval.start) {
res.back().end = max(res.back().end, newInterval.end);
fl = true;
}
}
if(!fl) res.push_back(newInterval);
return res;
}

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