-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0057. Insert Interval.cpp
More file actions
31 lines (29 loc) · 1.12 KB
/
Copy path0057. Insert Interval.cpp
File metadata and controls
31 lines (29 loc) · 1.12 KB
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
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>> &intervals, vector<int> &newInterval) {
// answer vector to return
vector<vector<int>> ans;
// loop through, O(n)
for (int i = 0; i < intervals.size(); i++) {
// new is after, so just add interval to answer
if (intervals[i][1] < newInterval[0]) {
ans.push_back(intervals[i]);
}
// new is before, so add new and update
else if (newInterval[1] < intervals[i][0]) {
ans.push_back(newInterval);
newInterval = intervals[i];
}
// new overlaps, so choose min for start, max for end
else if (newInterval[0] <= intervals[i][1] || intervals[i][0] <= newInterval[1]) {
if (intervals[i][0] < newInterval[0])
newInterval[0] = intervals[i][0];
if (intervals[i][1] > newInterval[1])
newInterval[1] = intervals[i][1];
}
}
// add and return
ans.push_back(newInterval);
return ans;
}
};