题解 | #牛舍扩建#
牛舍扩建
https://www.nowcoder.com/practice/2bb8208d18344608bc6bb19a78facad9
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param intervals int整型vector<vector<>> * @param new_interval int整型vector * @return int整型vector<vector<>> */ vector<vector<int> > insertNewInterval(vector<vector<int> >& intervals, vector<int>& new_interval) { // write code here if (new_interval[1] < intervals[0][0]) { intervals.insert(intervals.begin(), new_interval); return intervals; } if (new_interval[0] > intervals.back()[1]) { intervals.push_back(new_interval); } vector<vector<int>> ans; for (int i = 0; i < intervals.size(); i++) { if (intervals[i][1] < new_interval[0]) { ans.push_back(intervals[i]); continue; } if (new_interval[1] < intervals[i][0]) { ans.push_back(new_interval); for (int j = i; j < intervals.size(); j++) { ans.push_back(intervals[j]); } return ans; } int left = min(intervals[i][0], new_interval[0]); int right = max(intervals[i][1], new_interval[1]); ans.push_back({left, right}); int j; for (j = i+1; j < intervals.size(); j++) { if (intervals[j][0] <= ans.back()[1]) { ans.back()[1] = max(ans.back()[1], intervals[j][1]); continue; } break; } for (; j < intervals.size(); j++) { ans.push_back(intervals[j]); } break; } return ans; } };