我是靠谱客的博主 开放红牛,这篇文章主要介绍LeetCode57 插入区间,现在分享给大家,希望可以做个参考。

设置新插入的区间为pre,当pre和cur没交集且pre在前面(pre.end<cur.start),则添加pre,没交集且pre在后面(cur.end<pre.start),则添加cur。若有交集,则更新pre。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public List<Interval> insert(List<Interval> intervals, Interval newInterval) { List<Interval> list = new LinkedList<>(); Interval pre = newInterval; for(Interval curr: intervals){ if(pre.end < curr.start) { list.add(pre); pre = curr; } else if (curr.end < pre.start) { //Here is the difference. list.add(curr); } else { pre.start = Math.min(pre.start, curr.start); pre.end = Math.max(pre.end, curr.end); } } list.add(pre); return list; }

最后

以上就是开放红牛最近收集整理的关于LeetCode57 插入区间的全部内容,更多相关LeetCode57内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部