资讯专栏INFORMATION COLUMN

[LeetCode] Insert Interval

Jonathan Shieber / 2587人阅读

Problem

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].
Solution with new list
class Solution {
    public List insert(List intervals, Interval itvl) {
        List res = new ArrayList<>();
        if (intervals == null || intervals.size() == 0) {
            intervals.add(itvl);
            return intervals;
        }
        int i = 0;
        while (i < intervals.size() && intervals.get(i).end < itvl.start) {
            res.add(intervals.get(i++));
        }
        while (i < intervals.size() && intervals.get(i).start <= itvl.end) {
            itvl.start = Math.min(intervals.get(i).start, itvl.start);
            itvl.end = Math.max(intervals.get(i).end, itvl.end);
            i++;
        }
        res.add(itvl);
        while (i < intervals.size()) {
            res.add(intervals.get(i++));
        }
        return res;
    }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77070.html

相关文章

  • [Leetcode] Merge Intervals and Insert Interval 合并间

    摘要:我们只要把所有和该有重叠的合并到一起就行了。最后把前半部分的列表,合并后的大和后半部分的列表连起来,就是结果了。 Merge Intervals 最新更新请见 https://yanjia.me/zh/2019/02/... Given a collection of intervals, merge all overlapping intervals.For example, Gi...

    antyiwei 评论0 收藏0
  • leetcode--57--Insert Interval

    摘要:问题描述分析这道题的关键在于理解问题,抽取原型,理解中间可以部分如何界定,以及非部分如何进行追加。需要注意的是循环到最后一个元素和在最后一个元素的区别。 问题描述: Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You m...

    kycool 评论0 收藏0
  • leetcode57. Insert Interval

    摘要:题目要求给定一组顺序排列且相互之间没有重叠的区间,输入一个区间,将它插入到当前的区间数组中,并且将需要合并的区间合并,之后返回插入并且合并后的区间。我们将这三个类型的区间分别标注为类型,类型,类型。 题目要求 Given a set of non-overlapping intervals, insert a new interval into the intervals (merge...

    Yuanf 评论0 收藏0
  • 57. Insert Interval

    57. Insert Interval 题目链接:https://leetcode.com/problems... public class Solution { public List insert(List intervals, Interval newInterval) { // skip intervals which not overlap with new on...

    kid143 评论0 收藏0
  • leetcode436. Find Right Interval

    摘要:题目要求假设一个二维的整数数组中每一行表示一个区间,每一行的第一个值表示区间的左边界,第二个值表示区间的右边界。 题目要求 Given a set of intervals, for each of the interval i, check if there exists an interval j whose start point is bigger than or equal ...

    robin 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<