LeetCode 57. Insert Interval

原题链接在这里: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].

题解:

原题默认,原来的intervals 是sorted. 所以拿新的interval 和 list中的每一个interval比较即可。

分三种情况:1. newInterval 的 start 比现在遍历到的 curInterval.end 还大,说明要加的新interval 在后面才加,所以curInterval 加到 res 里.

2. newInterval 的end 比 curInterval 的start 还小,说明在应该在之前加,所以res 加上 newInterval, 然后把 curInterval 赋值给 newInterval.

3. 其他的情况就是说明有交集了,此时算 merged 后的interval, 取curInterval和newInterval中较小的start赋给merged, 较大的end赋给merged. 然后用merged 当成新的 newInterval.

Note: 第二种情况下必须把newInterval 加在res中,再把curInterval赋值给newInterval. 如果直接把 curInterval加在 res中,会造成新的res不是按顺序出现的.

e.g. {[1,5]}, newInterval = [0,0], 若是直接加了curInterval, 结果就是{[1,5] [0,0]} 是没有顺序的.

Time Complexity: O(intervals.size()).

Space: O(res.size()).

AC Java:

 1 /**
 2  * Definition for an interval.
 3  * public class Interval {
 4  *     int start;
 5  *     int end;
 6  *     Interval() { start = 0; end = 0; }
 7  *     Interval(int s, int e) { start = s; end = e; }
 8  * }
 9  */
10 public class Solution {
11     public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
12         List<Interval> res = new ArrayList<Interval>();
13         for(Interval curInterval : intervals){
14             if(curInterval.end < newInterval.start){
15                 res.add(curInterval);
16             }else if(curInterval.start > newInterval.end){
17                 res.add(newInterval);
18                 newInterval = curInterval;
19             }else{
20                 newInterval.start = Math.min(newInterval.start, curInterval.start);
21                 newInterval.end = Math.max(newInterval.end, curInterval.end);
22             }
23         }
24         res.add(newInterval);
25         return res;
26     }
27 }

类似Merge Intervals

posted @ 2015-10-16 22:51  Dylan_Java_NYC  阅读(293)  评论(0编辑  收藏  举报