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

     题目的意思:给定一个非重叠的区间,插入一个新的区间,如果区间与其他区间相交,则必须合并

    注意题目有个假设,区间根据start时间进行了排序,所以自己不需要排序

    struct Interval {
        int start;
        int end;
        Interval() : start(0), end(0) {}
        Interval(int s, int e) : start(s), end(e) {}
    };

    解题思路:设给定的区间为intervals,插入的区间为newInterval,只需要将newInterval与intervals相交的区间合并即可,

    如果newInterval与intervals没有相交的区间,则必须将newInterval插入到相应的位置

    本题有三种情况

      (1)如果intervals[i].end < newInterval.start,说明intervals[i]与newInterval不相交,保留即可

      (2)如果intervals[i].start > newInterval.end, 说明intervals[i]与newInterval不相交,将newInterval插入即可,注意这时候其后面的intervals[i],都可以保留,这是由于本身区间是不想交的。

       (3)  如果intervals[i].start < newInterval.end,说明区间相交,合并区间,更新newInterval

    class Solution {
    public:
        vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
            vector<Interval> res;
            for(int i = 0 ; i < intervals.size(); ++ i){
                if(intervals[i].end < newInterval.start) res.push_back(intervals[i]);
                else if(intervals[i].start > newInterval.end) {
                    res.push_back(newInterval);
                    newInterval = intervals[i];
                }else if(intervals[i].start <= newInterval.end ){
                    newInterval.start = min(newInterval.start, intervals[i].start);
                    newInterval.end =  max(newInterval.end, intervals[i].end);
                }
            }
            res.push_back(newInterval);
            return res;
        }
    };

      

        

     
  • 相关阅读:
    java中需要注意的小细节
    利用mysql查询总数据条数,再php处理数据转出数组,生成随机返回到页面,可以做成刷新页面,出现不同的内容
    js刷新页面方法大全
    CSS3自定义滚动条样式 -webkit-scrollbar(转)
    使用jquery.qrcode生成二维码(转)
    JS鼠标事件大全 推荐收藏
    微信小程序
    js几种生成随机颜色方法
    Canvas——使用定时器模拟动态加载动画!
    H5——表单验证新特性,注册模态框!
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3826195.html
Copyright © 2011-2022 走看看