题解 | #插入区间#
插入区间
https://www.nowcoder.com/practice/1d784b5472ab4dde88ea2331d16ee909
/** * struct Interval { * int start; * int end; * Interval(int s, int e) : start(start), end(e) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param Intervals Interval类vector * @param newInterval Interval类 * @return Interval类vector */ vector<Interval> insertInterval(vector<Interval>& Intervals, Interval newInterval) { // write code here vector<Interval> ans; if(Intervals.size()==0) { ans.push_back(newInterval); return ans; } if(Intervals.size()==1) { Interval tmp; tmp.start= min(Intervals[0].start,newInterval.start); tmp.end = max(newInterval.end,Intervals[0].end); ans.push_back(tmp); return ans; } for(int i=0;i<Intervals.size();i++) { if(Intervals[i].end>=newInterval.start && i+1 <Intervals.size() ) { if(Intervals[i+1].start<=newInterval.end ) { Interval tmp; tmp.start= min(Intervals[i].start,newInterval.start); while(Intervals[i].end<=newInterval.end && i+1 <Intervals.size()) i++; tmp.end = max(Intervals[i].end,newInterval.end); ans.push_back(tmp); } else if(Intervals[i+1].start>newInterval.end) { Interval tmp; tmp.start= min(Intervals[i].start,newInterval.start); tmp.end = newInterval.end; ans.push_back(tmp); } } else ans.push_back(Intervals[i]); } return ans; } };