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

leetcode | Insert Interval

时间:2015-07-25 21:36:35      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:interval

Insert Interval : https://leetcode.com/problems/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:
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分为3部分,完全处于newInterval之前的,和newInterval有重叠的,完全处于newInterval之后的。

  • 完全处于newInterval之前的 newInterval.start > intervals[i].end;
  • 和newInterval有重叠的 start = min(start, intervals[i].start); end = max(end, intervals[i].end);
  • 完全处于newInterval之后的 newInterval.end < intervals[i].satrt;
/**
 * 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) {
        int size = intervals.size();
        vector<Interval> res;
        int i = 0;
        int start = newInterval.start, end = newInterval.end;
        // 将newInterval之前的全部压入结果
        for (; i < size && start > intervals[i].end; i++) {
            res.push_back(intervals[i]);
        }
        if (i == size) {
            res.push_back(newInterval);
            return res;
        // 重叠区域
        start = min(start, intervals[i].start); // 和interval[i]有重叠
        for (; i < size && end >= intervals[i].start; i++) {
            end = max(end, intervals[i].end); // 所有重叠,直到end < intervals[i].start
        }
        res.push_back(Interval(start, end)); // 将新Interval入结果。(交叠后的newInterval)
        // 剩下的
        res.insert(res.end(), intervals.begin()+i, intervals.end()); 
        return res;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode | Insert Interval

标签:interval

原文地址:http://blog.csdn.net/quzhongxin/article/details/47059709

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