-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsert_Interval.cpp
More file actions
32 lines (27 loc) · 857 Bytes
/
Copy pathInsert_Interval.cpp
File metadata and controls
32 lines (27 loc) · 857 Bytes
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
#include "vector";
using namespace std;
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
int n = intervals.size();
int idx = 0;
vector<vector<int>> answer;
// find overlap
while (idx < n && intervals[idx][1] < newInterval[0]) {
answer.push_back(intervals[idx]);
idx++;
}
// merge overlapping intervals
while (idx < n && intervals[idx][0] <= newInterval[1]) {
newInterval[0] = min(newInterval[0], intervals[idx][0]);
newInterval[1] = max(newInterval[1], intervals[idx][1]);
idx++;
}
answer.push_back(newInterval);
while (idx < n) {
answer.push_back(intervals[idx]);
idx++;
}
return answer;
}
};