第一眼看上去,思路可以和Merge Intervals 一样,将newInterval合并到intervals之后,进行排序,然后输出。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public: vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) { intervals.push_back(newInterval); if(intervals.size()<=1) return intervals; sort(intervals.begin(),intervals.end(),[](vector<int> &a, vector<int> &b)->bool{ return a[0]<b[0]; }); vector<vector<int>> result; result.push_back(intervals[0]); for(int i=1;i<intervals.size();++i){ if(result.back()[1]>=intervals[i][0]){ result.back()[1]=max(result.back()[1],intervals[i][1]); }else{ result.push_back(intervals[i]); } } return result; } };
|