题意简述:给定若干个数轴上的闭区间,保证互不重合且有序,要求插入一个新的区间,并返回新的区间集合,保证有序且互不重合。
只想到了一个线性的解法,所有区间端点,只要被其他区间覆盖,就是不合法的,把他们去掉后,就可以直接得到答案。设新区间为【left,right】,那么,比left小的端点显然合法,比right大的端点显然也合法,left和right之间的端点显然不合法,然后判断Left和right是否合法即可。难度不大,代码有些细节需要注意。
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { vector<int> vec; for(int i=0;i<intervals.size();i++) { vec.push_back(intervals[i].start); vec.push_back(intervals[i].end); } int left=newInterval.start,right=newInterval.end; bool el=true,er=true; int i=0; vector<int>ans; while(i<vec.size()&&vec[i]<left) { ans.push_back(vec[i]); i++; } i--; while(i<0)i+=2; if((i%2)==1) ans.push_back(left); i=vec.size()-1; while(i>=0&&vec[i]>right) i--; i++; if((i%2)==0) ans.push_back(right); while(i<vec.size()) { ans.push_back(vec[i]); i++; } vector<Interval> anss; i=0; while(i<ans.size()) { Interval nn(ans[i],ans[i+1]); anss.push_back(nn); i+=2; } return anss; } };