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         Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
 4 
 5         List<int[]> merged = new ArrayList<>();
 6         merged.add(intervals[0]);
 7 
 8         for (int i = 1; i < intervals.length; i++) {
 9             int[] prev = merged.get(merged.size() - 1);
10             int[] interval = intervals[i];
11             if (interval[0] <= prev[1]) {
12                 prev[1] = Math.max(prev[1], interval[1]);
13             } else {
14                 merged.add(interval);
15             }
16         }
17         return merged.toArray(new int[0][0]);
18     }
19 }

 

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