57. Insert Interval
Solution#
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> result;
for (int i = 0; i < intervals.size(); i++) {
if (intervals[i][0] > newInterval[1]) {
// Outside before
result.push_back(newInterval);
result.insert(result.end(), intervals.begin() + i, intervals.end());
return result;
}
else if (intervals[i][1] < newInterval[0]) {
// Outside after
result.push_back(intervals[i]);
}
else {
// Overlap
int min = std::min(newInterval[0], intervals[i][0]);
int max = std::max(newInterval[1], intervals[i][1]);
newInterval[0] = min;
newInterval[1] = max;
}
}
result.push_back(newInterval);
return result;
}
};
Complexity#
- Time Complexity: O(N), where N is the size of
intervals
.
- Space Complexity: O(N), where N is the size of
result
.
All Solutions