凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 57. Insert Interval

分类:algorithm| 发布时间:2017-02-24 07:49:00


题目

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].

题意

给出一组没有间距的数字,插入一个新的间隙(如果有必要需要进行合并)。

解法

/**
 * 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) {
        vector<Interval> ret;
        ret.reserve(intervals.size() + 1);
        int i = 0;
        const int n = intervals.size();
        for (; i < n; ++i) {
            Interval &tmp = intervals[i];
            if (newInterval.start <= tmp.start && newInterval.end >= tmp.start) {
                newInterval.end = max(newInterval.end, tmp.end);
                continue;
            }

            if (tmp.start <= newInterval.start && tmp.end >= newInterval.start) {
                newInterval.start = tmp.start;
                newInterval.end = max(newInterval.end, tmp.end);
                continue;
            }

            if (tmp.start > newInterval.start) {
                break;
            }

            ret.push_back(tmp);
        }

        ret.push_back(newInterval);
        for (; i < n; ++i) {
            ret.push_back(intervals[i]);
        }

        return ret;
    }
};