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

[LeetCode] Insert Interval

时间:2015-07-06 19:35:45      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

There are mainly two solutions to this problem. The first one is of O(n) time. Its idea is to compare each interval in intervals (intervals[i]) with newInterval and then perform respective operations according to their relative locations.

  1. If they are overlapped, merge them to newInterval;
  2. If interval[i] is to the left of newInterval, push intervals[i] to the result vector;
  3. If newInterval is to the left of intervals[i], push newInterval and all the remaining intervals (intervals[i], ..., intervals[n - 1]) to the result vector.

The code is as follows.

 1 class Solution {
 2 public:
 3     vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
 4         vector<Interval> res;
 5         int n = intervals.size();
 6         for (int i = 0; i < n; i++) {
 7             if (!isOverlap(intervals[i], newInterval)) {
 8                 if (intervals[i].end < newInterval.start)
 9                     res.push_back(intervals[i]);
10                 else {
11                     res.push_back(newInterval);
12                     for (int j = i; j < n; j++)
13                         res.push_back(intervals[j]);
14                     return res;
15                 }
16             }
17             else newInterval = merge(intervals[i], newInterval);
18         }
19         res.push_back(newInterval);
20         return res;
21     }
22 private:
23     bool isOverlap(Interval interval1, Interval interval2) {
24         return !(interval1.start > interval2.end || interval2.start > interval1.end);
25     }
26     Interval merge(Interval interval1, Interval interval2) {
27         int start = min(interval1.start, interval2.start);
28         int end = max(interval1.end, interval2.end);
29         return Interval(start, end);
30     }
31 };

The second solution is of O(logn) and will come out soon...

[LeetCode] Insert Interval

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4625034.html

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