【Leetcode】Insert Interval
来源:互联网 发布:mysql中text最大长度 编辑:程序博客网 时间:2024/05/19 02:41
题目链接:https://leetcode.com/problems/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]
.
思路:
插入一个结点就相当于在一个整体大部分有序,仅仅在插入位置附近需要更新区间。
考虑跟上题很相似,直接将元素插入list,再调用merge方法。因为有排序过程,算法时间复杂度为O(nlogn),空间复杂度为O(n)。
拿上题代码改改就试着提交。。结果居然ac了23333,说明能通过leetcode测试用例。
本题肯定能进一步优化的,因为对一个有序数组插入一个元素时间复杂度应该是O(n),有时间用这种思路做。
算法:
public List<Interval> insert(List<Interval> intervals, Interval newInterval) { intervals.add(newInterval); return merge(intervals); } class LinkedNode {Interval val;LinkedNode next;public LinkedNode(Interval val, LinkedNode next) {this.val = val;this.next = next;}}public List<Interval> merge(List<Interval> intervals) {List<Interval> res = new ArrayList<Interval>();if (intervals == null || intervals.size() == 0)return res;// 按照区间的起点进行排序Collections.sort(intervals, new Comparator<Interval>() {public int compare(Interval o1, Interval o2) {if (o1.start > o2.start) {return 1;} else if (o1.start < o2.start) {return -1;} else {return 0;}}});// 改为链表结构Interval headv = new Interval(0, 0);LinkedNode head = new LinkedNode(headv, null);LinkedNode p = head;for (Interval v : intervals) {LinkedNode node = new LinkedNode(v, null);p.next = node;p = node;}// 检查、合并LinkedNode v1, v2;v1 = head.next;while (v1.next != null) {v2 = v1.next;if (v1.val.end >= v2.val.start) {// 交叉if (v1.val.end >= v2.val.end) {// v1包含v2v1.next = v2.next;} else {// 非包含的交叉// res.add(new Interval(v1.start,v2.end));v1.next = v2.next;v1.val.end = v2.val.end;}} else {v1 = v1.next;}}p = head.next;while (p != null) {res.add(p.val);p = p.next;}return res;}
- LeetCode: Insert Interval & Merge Interval
- LeetCode题目 Insert Interval
- LeetCode: Insert Interval
- LeetCode Insert Interval
- LeetCode: Insert Interval
- Leetcode: Insert Interval
- [LeetCode] Insert Interval
- LeetCode Insert Interval
- [LeetCode]Insert Interval
- leetcode insert interval
- [leetcode]Insert Interval
- LeetCode-Insert Interval
- [leetcode] Insert Interval
- LeetCode - Insert Interval
- 【leetcode】Insert Interval
- leetcode Insert Interval
- 【leetcode】Insert Interval
- LeetCode Insert Interval
- 使用JavaMail创建邮件和发送邮件
- 菜鸟成长记-仿今日头条雏形
- 【MyBatis框架点滴】——MyBatis一对一查询
- Tachyon:Spark生态系统中的分布式内存文件系统
- 排序算法
- 【Leetcode】Insert Interval
- struts和springmvc相关获取ServletContext()方式
- Mockplus
- HP电脑 VMware Workstation Pro装Centos6.7 报错
- JavaScript基础——面向对象的程序设计(一)创建对象的几种方式总结
- 【算法总结系列-6】深度优先搜索-Depth First Search,DFS
- 基因数据处理49之cloud-scale-bwamem运行成功
- 将Web应用性能提高十倍的10条建议
- [arcengine][栅格]保存为本地文件