Insert intervals
題目:
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:
Given intervals?[1,3],[6,9], insert and merge?[2,5]?in as?[1,5],[6,9].
Example 2:
Given?[1,2],[3,5],[6,7],[8,10],[12,16], insert and merge?[4,9]?in as?[1,2],[3,10],[12,16].
This is because the new interval?[4,9]?overlaps with?[3,5],[6,7],[8,10].
?
思路: 對于intervals從頭到尾遍歷,用new interval與相應的interval[i]對比,如果整個new interval都在interval[i]的左邊,就把new interval存到result里,然后把剩下的所有interval都存起來即可,如果new interval在interval[i]的右邊,則存起來interval[i],然后繼續遍歷; 如果new interval 和 interval[i]有overlap, 則將兩者進行合并,然后繼續遍歷。
?
代碼:?
1 class Solution { 2 public: 3 vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 vector<Interval> result; 7 8 for (int i = 0; i<intervals.size(); i++){ 9 10 if (intervals[i].end < newInterval.start) 11 result.push_back(intervals[i]); 12 else if (intervals[i].start>newInterval.end){ 13 14 result.push_back(newInterval); 15 while (i<intervals.size()){ 16 17 result.push_back(intervals[i]); 18 i++; 19 } 20 } 21 22 else{ 23 24 newInterval.start = min(intervals[i].start, newInterval.start); 25 newInterval.end = max(intervals[i].end, newInterval.end); 26 27 } 28 } 29 30 if(0 == result.size() || result.back().end < newInterval.start) 31 result.push_back(newInterval); 32 33 return result; 34 } 35 };?
轉載于:https://www.cnblogs.com/tanghulu321/archive/2013/05/11/3072348.html
總結
以上是生活随笔為你收集整理的Insert intervals的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c# treeView 取消选择事件
- 下一篇: 使用c#类库绘制柱状图