zoukankan      html  css  js  c++  java
  • leetcode93:insert-interval

    题目描述

    给定一组不重叠的时间区间,在时间区间中插入一个新的时间区间(如果有重叠的话就合并区间)。
    这些时间区间初始是根据它们的开始时间排序的。
    示例1:
    给定时间区间[1,3],[6,9],在这两个时间区间中插入时间区间[2,5],并将它与原有的时间区间合并,变成[1,5],[6,9].
    示例2:
    给定时间区间[1,2],[3,5],[6,7],[8,10],[12,16],在这些时间区间中插入时间区间[4,9],并将它与原有的时间区间合并,变成[1,2],[3,10],[12,16].
    这是因为时间区间[4,9]覆盖了时间区间[3,5],[6,7],[8,10].

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

    链接:https://www.nowcoder.com/questionTerminal/02418bfb82d64bf39cd76a2902db2190?f=discussion
    来源:牛客网

    class Solution {
    public:
        vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
            vector<Interval> res;
            int i=0;
            for(;i<intervals.size();i++){
                if(newInterval.end<intervals[i].start)
                    break;
                else if(newInterval.start>intervals[i].end)
                    res.push_back(intervals[i]);
                else{
                    newInterval.start=min(newInterval.start,intervals[i].start);
                    newInterval.end=max(newInterval.end,intervals[i].end);
                }
              
        }
             
            res.push_back(newInterval);
            for(;i<intervals.size();i++)
                res.push_back(intervals[i]);
        return res;
        }
    };
  • 相关阅读:
    LamBda学习(一)
    如何返回一个只读泛型集合
    Socket编程笔记同步
    如何快速读取大文件(看csdn一网友要求写的)没有测试具体的速度。
    如何实现项目脚本的批量生成
    如何实现WORD查找完成后不提示的代码
    W32/Pate.a 病毒处理小记
    在WORD中用VBA实现光标移动与内容选择
    2. WCF 消息操作
    3. WCF 异常处理
  • 原文地址:https://www.cnblogs.com/hrnn/p/13417140.html
Copyright © 2011-2022 走看看