zoukankan      html  css  js  c++  java
  • 57. 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:

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

    解题思路:

    新的interval(newInterval)与现在的interval(cur)之间的关系有以下几种:

      1. cur.end < newInterval.start: 此时两个interval不重合,我们可以先将cur插入到返回数组中

      需要注意的是:现在不能够插入newInterval 因为后面的interval也有可能比它小

      2.cur.start > newInterval.end: 此时说明newInterval整体小于cur,我们要先将newInterval插入,然后再把cur插入

      3.cur和newInterval相交叉:首先merge两个interval并将新的interval作为newInterval继续尝试插入

    需要注意的是:

      1.为了防止反复插入newInterval,我用了一个bool变量(ist)来标记newInterval是否已经被插入过

      2.很有可能所有的interval都比newInterval要小,所以我们要记得最后根据ist来判断newInterval是否被插入,如果没有,就要插入。

    代码:

    /**
     * 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;
            bool ist = false;
            for(int i = 0; i < intervals.size(); i++){
                Interval cur = intervals[i];
                if(cur.end < newInterval.start){
                    ret.push_back(cur);
                    continue;
                }
                if(cur.start > newInterval.end){
                    if(!ist){
                        ret.push_back(newInterval);
                        ist = true;
                    }
                    ret.push_back(cur);
                    continue;
                }
                //need to merge
                newInterval.start = min(cur.start, newInterval.start);
                newInterval.end = max(cur.end, newInterval.end); 
            }
            if(!ist){
                ret.push_back(newInterval);
            }
            return ret;
        }
    };
  • 相关阅读:
    Docker界面化管理
    搭建MQTT服务器(Docker版)
    VS Code Markdown文件实时预览
    Nginx直接处理接口请求,返回相应内容(带html标签)
    Docker(九): 安装MySQL主从复制
    feign的一个注解居然隐藏这么多知识!
    使用Magisk指令修改 ro.debuggable(不刷机)
    【钓鱼可用】文件名反转字符串
    android高级UI之贝塞尔曲线<下>--贝塞尔曲线运用:QQ消息气泡
    英文阅读技巧操练---Article 1:The Product-Minded Software Engineer《一》
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9175899.html
Copyright © 2011-2022 走看看