LeetCode OJ 57 Insert Interval [hard]
来源:互联网 发布:淘宝买家信誉快速 编辑:程序博客网 时间:2024/05/28 23:20
题目描述:
Given a set of non-overlappingintervals, insert a new interval into the intervals (merge if necessary).
You may assume thatthe intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insertand 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 thenew interval [4,9] overlaps with [3,5],[6,7],[8,10].
理解:
给定一个区间组成的集合,插入衣蛾新的区间到集合中,合并需要合并的区间
This is because thenew interval [4,9] overlaps with [3,5],[6,7],[8,10].
分析:
将新的区间加入到区间集合中,再升序排序,按照题目56的方法进行合并;
解答:
public static class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; }}public static List<Interval> insert(List<Interval> intervals, Interval newInterval) { List<Interval> ans = new ArrayList<>(); intervals.add(newInterval); Collections.sort(intervals, new Comparator<Interval>() { @Override public int compare(Interval o1, Interval o2) { return Integer.compare(o1.start, o2.start); } }); int start = intervals.get(0).start; int end = intervals.get(0).end; for (int i = 1; i < intervals.size(); i++) { if (end >= intervals.get(i).start) { end = Math.max(end, intervals.get(i).end); } else { ans.add(new Interval(start, end)); start = intervals.get(i).start; end = intervals.get(i).end; } } ans.add(new Interval(start, end)); return ans;}
阅读全文
0 0
- LeetCode OJ 57 Insert Interval [hard]
- [Leetcode 57, Hard] Insert Interval
- LeetCode OJ:Insert Interval
- LeetCode OJ - Insert Interval
- LeetCode OJ Insert Interval
- Hard 57题 Insert Interval
- leetcode || 57、Insert Interval
- Leetcode#57||Insert Interval
- leetcode 57: Insert Interval
- leetcode 57:Insert Interval
- LeetCode 57 - Insert Interval
- Leetcode 57 Insert Interval
- LeetCode #57: Insert Interval
- Leetcode 57 Insert Interval
- Leetcode 57 Insert Interval
- LeetCode 57 Insert Interval
- LeetCode 57 --- Insert Interval
- leetcode-57 insert interval
- php基础学习
- 新建maven工程时报错:Could not resolve archetype org.apache.maven.archetypes .
- Bellman-Ford算法求解单源最短路径Java实现
- Spring五个事务隔离级别和七个事务传播行为
- Python-类与对象-子类扩展父类属性
- LeetCode OJ 57 Insert Interval [hard]
- API-集合框架(1)-介绍
- 实现安卓计时器
- C++中this指针详解
- android Studio 导入 早期项目 遇到refreshing gradle project
- 使用m2eclipse为eclipse集成Maven
- Context的理解
- javascript之数据类型与变量
- ActiveMQ发布订阅模式