leetcode -- Merge Intervals

6082 ワード

Given a collection of intervals, merge all overlapping intervals.
For example,Given  [1,3],[2,6],[8,10],[15,18] ,return  [1,6],[8,10],[15,18] .
[問題を解く考え方]
ここではInsert intervalの解題プロセスを使用して、マージするintervalを順次挿入します.
 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 ArrayList<Interval> merge(ArrayList<Interval> intervals) {
12         // Start typing your Java solution below
13         // DO NOT write main() function
14         ArrayList<Interval> result = new ArrayList<Interval>();
15         for(int i = 0; i < intervals.size(); i++){
16             result = insert(result, intervals.get(i));
17         }
18         return result;
19     }
20     
21     public ArrayList<Interval> insert(ArrayList<Interval> intervals,
22             Interval newInterval) {
23         ArrayList<Interval> result = new ArrayList<Interval>();
24         for (int i = 0; i < intervals.size(); i++) {
25             Interval tmp = intervals.get(i);
26             if (newInterval.end < tmp.start) {
27                 result.add(newInterval);
28                 for(int j = i; j < intervals.size(); j++){
29                     result.add(intervals.get(j));
30                 }
31                 return result;
32             } else if (newInterval.start > tmp.end) {
33                 result.add(tmp);
34                 continue;
35             } else {
36                 newInterval.start = Math.min(tmp.start, newInterval.start);
37                 newInterval.end = Math.max(tmp.end, newInterval.end);
38             }
39         }
40         result.add(newInterval);
41         return result;
42     }
43 }