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

[解题思路]

新建一个ArrayList来保存得到的结果。因为对原来的集合进行操作时如下情况需要额外的操作:newInterval插入当前interval之前

1.newInterval.end < curInterval.start, 插入

2.newInterval.end > curInterval.start, continue

3.newInterval 与 curInterval 重合,合并得到新的newInterval 

 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 static ArrayList<Interval> insert(ArrayList<Interval> intervals,
12             Interval newInterval) {
13         ArrayList<Interval> result = new ArrayList<Interval>();
14         for (int i = 0; i < intervals.size(); i++) {
15             Interval tmp = intervals.get(i);
16             if (newInterval.end < tmp.start) {
17                 result.add(newInterval);
18                 for(int j = i; j < intervals.size(); j++){
19                     result.add(intervals.get(j));
20                 }
21                 return result;
22             } else if (newInterval.start > tmp.end) {
23                 result.add(tmp);
24                 continue;
25             } else {
26                 newInterval.start = Math.min(tmp.start, newInterval.start);
27                 newInterval.end = Math.max(tmp.end, newInterval.end);
28             }
29         }
30         result.add(newInterval);
31         return result;
32     }
33 }

 

posted @ 2013-08-12 22:08  feiling  阅读(229)  评论(0编辑  收藏  举报