leetcode -- Merge Intervals

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 }

 

你可能感兴趣的:(LeetCode)