forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
insert-interval.cpp
35 lines (32 loc) · 1.06 KB
/
insert-interval.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
// Time: O(n)
// Space: O(1)
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
size_t i = 0;
vector<Interval> result;
// Insert intervals appeared before newInterval.
while (i < intervals.size() && newInterval.start > intervals[i].end) {
result.emplace_back(intervals[i++]);
}
// Merge intervals that overlap with newInterval.
while (i < intervals.size() && newInterval.end >= intervals[i].start) {
newInterval = {min(newInterval.start, intervals[i].start),
max(newInterval.end, intervals[i].end)};
++i;
}
result.emplace_back(newInterval);
// Insert intervals appearing after newInterval.
result.insert(result.end(), intervals.cbegin() + i, intervals.cend());
return result;
}
};