19.2.9 [LeetCode 57] Insert Interval
作者:互联网
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]]
Example 2:
Input: intervals =[[1,2],[3,5],[6,7],[8,10],[12,16]]
, newInterval =[4,8]
Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval[4,8]
overlaps with[3,5],[6,7],[8,10]
.
题意
给定一组以左边界大小排列的互不重合的闭区间,求加入一个新区间后的集合(也需要从小到大排列)
题解
一开始做的十分复杂
1 class Solution { 2 public: 3 vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { 4 if (intervals.size() < 1) { 5 intervals.push_back(newInterval); 6 return intervals; 7 } 8 int s = newInterval.start, e = newInterval.end, i; 9 for (i = 0; i < intervals.size(); i++) { 10 if (intervals[i].start <= s && intervals[i].end >= s) { 11 if (e <= intervals[i].end) 12 return intervals; 13 break; 14 } 15 else if (intervals[i].start > s) { 16 if(intervals[i].start>e) { 17 intervals.insert(intervals.begin()+i,newInterval); 18 return intervals; 19 } 20 intervals[i].start = s; 21 if (e <= intervals[i].end) 22 return intervals; 23 break; 24 } 25 } 26 int mark = i; 27 i++; 28 for (; i < intervals.size(); ) { 29 if (intervals[i].start > e) { 30 intervals[mark].end = e; 31 return intervals; 32 } 33 else if (intervals[i].end >= e) { 34 intervals[mark].end = intervals[i].end; 35 intervals.erase(intervals.begin() + i); 36 return intervals; 37 } 38 intervals.erase(intervals.begin() + i); 39 } 40 if(mark>=intervals.size()) 41 intervals.push_back(newInterval); 42 else 43 intervals[mark].end = e; 44 return intervals; 45 } 46 };View Code
需要考虑很多条件,于是重写
1 class Solution { 2 public: 3 vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { 4 int i = 0, s = newInterval.start, e = newInterval.end; 5 vector<Interval>ans; 6 while (i < intervals.size() && intervals[i].end < s) { 7 ans.push_back(intervals[i]); 8 i++; 9 } 10 int left = s, right = e; 11 while (i < intervals.size() && intervals[i].start <= e) { 12 left = min(left, intervals[i].start); 13 right = max(right, intervals[i].end); 14 i++; 15 } 16 ans.push_back(Interval(left, right)); 17 while (i < intervals.size()) { 18 ans.push_back(intervals[i]); 19 i++; 20 } 21 return ans; 22 } 23 };View Code
这个就快得多了……
标签:Insert,newInterval,end,57,Interval,start,intervals,return,size 来源: https://www.cnblogs.com/yalphait/p/10357529.html