Skip to content

Instantly share code, notes, and snippets.

@adamkorg
Created September 23, 2019 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamkorg/6fcf6ef13a04ab6967c6af3b4762be72 to your computer and use it in GitHub Desktop.
Save adamkorg/6fcf6ef13a04ab6967c6af3b4762be72 to your computer and use it in GitHub Desktop.
Leetcode 57: Insert Interval
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> vout;
bool inserted = false;
vector<int> write(2,0);
for (int i=0; i<intervals.size(); ++i) {
if (!inserted) {
if (newInterval[1] < intervals[i][0]) { //newInterval before current
vout.push_back(newInterval);
vout.push_back(intervals[i]);
inserted = true;
}
else if (newInterval[1] >= intervals[i][0] && newInterval[1] <= intervals[i][1]) { //overlap <-
write[0] = min(newInterval[0], intervals[i][0]);
write[1] = intervals[i][1];
vout.push_back(write);
inserted = true;
continue;
}
else if (newInterval[0] >= intervals[i][0] && newInterval[0] <= intervals[i][1]) { //overlap ->
write[0] = intervals[i][0];
write[1] = max(newInterval[1], intervals[i][1]);
vout.push_back(write);
inserted = true;
continue;
}
else if (newInterval[0] < intervals[i][0] && newInterval[1] > intervals[i][1]) { //overlap <-->
vout.push_back(newInterval);
inserted = true;
continue;
}
}
if (vout.size()>0 && vout[vout.size()-1][1] >= intervals[i][0]) { //merge previous
vout[vout.size()-1][1] = max(vout[vout.size()-1][1], intervals[i][1]);
}
else // doesn't overlap, so just write out.
vout.push_back(intervals[i]);
}
if (!inserted) //add newInterval to end of return array
vout.push_back(newInterval);
return vout;
}
void printv(const vector<vector<int>>& v) {
for (auto r : v)
cout << "[" << r[0] << "," << r[1] << "] ";
cout << "\n";
}
int main() {
vector<vector<int>> intervals {{0,2},{3,9}}; //{{1,2},{3,5},{6,7},{8,10},{12,16}}; //{{1,3},{6,9}};
vector<int> newInterval {6,8}; //{4,8}; //{2,5};
auto vals = insert(intervals, newInterval);
printv(vals);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment