【leetcode】- Insert Interval(插入一个区间)

1、题目描述

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:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

2、问题描述:

  • 给一个区间数组,插入一个区间,如果有重叠那么合并,否则,直接插入。

3、问题关键:

  • 分情况讨论,区间在最前面,区间在最后面,区间在中间。

4、C++代码:

/**
 * 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> res;
        bool has_in = false;
        for (auto interval : intervals) {
            if (interval.start > newInterval.end) {//因为区间是安装start排序的,如果start大于,那么new在所有的前面,直接插入。
                if (!has_in){
                    res.push_back(newInterval);
                    has_in = true;
                }
                res.push_back(interval);
            }
            if (interval.end < newInterval.start)//当前的区间在要插入的区间的后面。
                res.push_back(interval);
            else {//当前区间和要插入的区间有重叠。
                newInterval.start = min(interval.start, newInterval.start);
                newInterval.end = max(interval.end, newInterval.end);
            }
        }
        if (!has_in) res.push_back(newInterval);//new在所有的后面。
        return res;
    }
};
    原文作者:邓泽军_3679
    原文地址: https://www.jianshu.com/p/ab72378f2461
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞