这道题。。。。简直了。。。
新博文地址:[leetcode]Insert Interval
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].
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].
这道题不难,就是烦,考虑了各种cover的组合情况,代码繁杂,看着就不对劲,网上搜了一下,找到了这样一个犀利的解法,抽象、简洁、易懂,真经典
public List<Interval> insert(List<Interval> intervals, Interval newInterval) { List<Interval> list = new LinkedList<Interval>(); if(intervals == null || intervals.isEmpty()){ list.add(newInterval); return list; } if(newInterval == null) return intervals; int newStart = newInterval.start,newEnd = newInterval.end; int i = 0; for(; i < intervals.size() && intervals.get(i).end < newInterval.start; i++){ list.add(intervals.get(i)); } if(i < intervals.size()){ newStart = Math.min(intervals.get(i).start,newStart); } for(; i < intervals.size() && newEnd >= intervals.get(i).start; i++){ newEnd = Math.max(newEnd, intervals.get(i).end); } list.add(new Interval(newStart, newEnd)); for(;i < intervals.size(); i++){ list.add(intervals.get(i)); } return list; }
相关推荐
刷LeetCode刷LeetCode刷LeetCode刷LeetCode刷LeetCode
大佬的leetcode刷题笔记(c++版本)
vs code LeetCode 插件
LeetCode 101_C++_算法_leetcode_leetcode101_leetcode101.zip
leetcode中文版
LeetCode 101_C++_算法_leetcode_leetcode101_leetcode101_源码.zip
100个leetCode详细解答
LeetCode 刷题汇总1
LeetCode 选讲1
terminal-leetcode, 终端Leetcode是基于终端的Leetcode网站查看器 终端 leetcode终端leetcode是基于终端的leetcode网站查看器。本项目是由 RTV 激发的。 我最近正在学习本地化的反应,以实践我的新知识,并根据这个...
leetcode刷题, 直接用leetcode的分类方式.
该分类为结合《算法导论》的内容,给出Leetcode题目分类。题目主要集中在Leetcode的前400题中,也包括有后面的一些经典值得刷的题。该题目分类按照算法和数据结构排版,即可供单独Leetcode刷题使用,也可以配合学习...
这份文档列出了leetcode几乎所有题目(大约134题)的分类以及难度指示,是刷leetcode的必备良品。现在leetcode总的题目数已经达到150题,所以有部分题目没有包含在这个文档中,但是——足够了。po主刷leetcode的时候...
leetcode高频面试笔试题150+道,亲身总结。
LeetCode面试笔试题
LeetCode 刷题笔记
(C++)LeetCode刷题题解答案
LeetCode 刷题
leetcode全套解答python版本。包括更新到10月份的的leetcode
这个是leetcode发布的ebook 包含有常见题目的解答以及讲解