56. Insert Interval & Merge Intervals

Insert Intervals

Given a non-overlapping interval list which is sorted by start point.

Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary).

Example

Insert [2, 5] into [[1,2], [5,9]], we get [[1,9]].

Insert [3, 4] into [[1,2], [5,9]], we get [[1,2], [3,4], [5,9]].

分析:

Create a new array list, insert the smaller interval in the new array and use a counter to keep track of the total number of smaller intervals. If we find an interval overlapping with the new one, we need to change the start and end.

 1 class Solution {
 2     public int[][] insert(int[][] intervals, int[] newInterval) {
 3         List<int[]> resultList = new ArrayList<>();
 4         boolean hasInserted = false;
 5         for (int[] interval : intervals) {
 6             if (interval[0] > newInterval[1]) {
 7                 if (!hasInserted) {
 8                     resultList.add(newInterval);
 9                     hasInserted = true;
10                 }
11                 resultList.add(interval);
12             } else if (interval[1] < newInterval[0]) {
13                 resultList.add(interval);
14             } else {
15                 newInterval[0] = Math.min(newInterval[0], interval[0]);
16                 newInterval[1] = Math.max(newInterval[1], interval[1]);
17             }
18         }
19         
20         if (!hasInserted) {
21             resultList.add(newInterval);
22         }
23         
24         return resultList.toArray(new int[0][0]);
25     }
26 }

 

Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

Example

Given intervals => merged intervals:

[                     [
  [1, 3],               [1, 6],
  [2, 6],      =>       [8, 10],
  [8, 10],              [15, 18]
  [15, 18]            ]
]

Analyze:

Sort first, then merge intervals if they overlap.
 1 class Solution {
 2     public int[][] merge(int[][] intervals) {
 3         if (intervals.length <= 1) {
 4             return intervals;
 5         }
 6         // Sort by ascending starting point
 7         Arrays.sort(intervals, (i1, i2) -> Integer.compare(i1[0], i2[0]));
 8 
 9         List<int[]> result = new ArrayList<>();
10         int[] newInterval = intervals[0];
11         result.add(newInterval);
12         for (int[] interval : intervals) {
13             if (interval[0] <= newInterval[1]) {
14                 newInterval[1] = Math.max(newInterval[1], interval[1]);
15             } else {
16                 newInterval = interval;
17                 result.add(interval);
18             }
19         }
20         return result.toArray(new int[result.size()][]);
21     }
22 }

 

posted @ 2016-07-14 03:57  北叶青藤  阅读(252)  评论(0编辑  收藏  举报