-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsert Interval.cpp
More file actions
31 lines (27 loc) · 1011 Bytes
/
Copy pathInsert Interval.cpp
File metadata and controls
31 lines (27 loc) · 1011 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
// User function Template for C++
class Solution {
public:
vector<vector<int>> insertInterval(vector<vector<int>> &intervals,
vector<int> &newInterval) {
vector<vector<int>> result;
int i = 0, n = intervals.size();
// Add intervals that come before the new interval
while (i < n && intervals[i][1] < newInterval[0]) {
result.push_back(intervals[i]);
i++;
}
// Merge overlapping intervals with the new interval
while (i < n && intervals[i][0] <= newInterval[1]) {
newInterval[0] = min(newInterval[0], intervals[i][0]);
newInterval[1] = max(newInterval[1], intervals[i][1]);
i++;
}
result.push_back(newInterval);
// Add remaining intervals that come after the new interval
while (i < n) {
result.push_back(intervals[i]);
i++;
}
return result;
}
};