【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;}


1 0
原创粉丝点击