[leetcode] 57. Insert Interval

556 篇文章 2 订阅
441 篇文章 0 订阅

Description

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

分析

题目的意思是:给你一堆区间,现在再加一个区间,然后把相互覆盖的区间合并。最后输出结果。

  • 思想就是找到那些要合并的区间,然后合并之后加入结果集合就行了。

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;
        int n=intervals.size();
        int cur=0;
        while(cur<n&&intervals[cur].end<newInterval.start){
            res.push_back(intervals[cur++]);
        }
        while(cur<n&&intervals[cur].start<=newInterval.end){
            newInterval.start=min(intervals[cur].start,newInterval.start);
            newInterval.end=max(intervals[cur].end,newInterval.end);
            cur++;
        }
        res.push_back(newInterval);
        for(int i=cur;i<n;i++){
            res.push_back(intervals[i]);
        }
        return res;
    }
};

Python 代码

没什么说的,分三种情况分别讨论就行了,注意最后插入的位置要用flag记录一下,不然会有重复插入新区间。

class Solution:
    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        left=newInterval[0]
        right = newInterval[1]
        flag=True
        res=[]
        for i in range(len(intervals)):
            if intervals[i][0]>right:
                if flag:
                    res.append([left,right])
                    flag=False
                res.append(intervals[i])
            elif intervals[i][1]<left:
                res.append(intervals[i])
            else:
                left=min(left,intervals[i][0])
                right=max(right,intervals[i][1])
        if flag:
            res.append([left,right])
        return res

参考文献

[编程题]insert-interval

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值