码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Insert Inverval

时间:2015-03-20 06:50:10      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

Similar to merge intervals. But this is easier than merge interval, because every side is kind of "sorted".

 1 /**
 2  * Definition for an interval.
 3  * struct Interval {
 4  *     int start;
 5  *     int end;
 6  *     Interval() : start(0), end(0) {}
 7  *     Interval(int s, int e) : start(s), end(e) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
13         vector<Interval> result;
14         if (intervals.size() == 0) {
15             result.push_back(newInterval);
16             return result;
17         }
18         queue<int> left, right;
19         int len = intervals.size();
20         bool lf = true, rf = true;
21         for (int i = 0; i < len; i++) {
22             if (lf && newInterval.start < intervals[i].start) {
23                 left.push(newInterval.start);
24                 lf = false;
25             }
26             if (rf && newInterval.end < intervals[i].end) {
27                 right.push(newInterval.end);
28                 rf = false;
29             }
30             left.push(intervals[i].start);
31             right.push(intervals[i].end);
32         }
33         if (lf) left.push(newInterval.start);
34         if (rf) right.push(newInterval.end);
35         while (!left.empty()) {
36             int s = left.front(), e = right.front();
37             left.pop(), right.pop();
38             while (!left.empty()) {
39                 if (e >= left.front()) {
40                     e = right.front();
41                     left.pop(), right.pop();
42                 } else break;
43             }
44             result.push_back(Interval(s, e));
45         }
46         return result;
47     }
48 };

 

LeetCode – Refresh – Insert Inverval

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4352578.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!