LeetCode Insert Interval
发布日期:2022-03-12 04:49:26 浏览次数:51 分类:技术文章

本文共 2235 字,大约阅读时间需要 7 分钟。

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

题意:合并一个区间。

思路:分情况看:首先假设对于new,end < cur.start,那么就非常easy的知道应该插入cur的前面:相反,此时假设new.start > cur.end的话。那么就能继续往下走了。否则就是这种情况:此时两个区间是有重叠的。各自取左右边界的最小和最大值。

package code;import java.util.ArrayList;import java.util.List;import java.util.ListIterator;public class Insert_Interval {		public static void main(String[] args) {		List
intervals = new ArrayList
(); Insert_Interval root = new Insert_Interval(); Insert_Interval.Interval s1 = root.new Interval(1, 3); intervals.add(s1); intervals.add(new Insert_Interval().new Interval(6, 9)); Insert_Interval.Interval t = root.new Interval(2, 5); Insert_Interval.Solution solution = root.new Solution(); List
ans = solution.insert(intervals, t); for (Interval interval : ans) { System.out.println(interval.start + "-" + interval.end); } } public class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } } public class Solution { public List
insert(List
intervals, Interval newInterval) { if (intervals == null || newInterval == null) return intervals; if (intervals.size() == 0) intervals.add(newInterval); ListIterator
it = intervals.listIterator(); while (it.hasNext()) { Interval tmp = it.next(); if (newInterval.end < tmp.start) { it.previous(); it.add(newInterval); return intervals; } else { if (newInterval.start > tmp.end) continue; else { newInterval.start = Math.min(tmp.start, newInterval.start); newInterval.end = Math.max(tmp.end, newInterval.end); it.remove(); } } } intervals.add(newInterval); return intervals; } }}

版权声明:本文博客原创文章,博客,未经同意,不得转载。

转载于:https://www.cnblogs.com/zfyouxi/p/4741475.html

转载地址:https://blog.csdn.net/weixin_30348519/article/details/98162429 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:微信公众号订阅号与微信服务号区别
下一篇:Oracle之Check约束实例具体解释

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年03月26日 18时20分50秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章