#56 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]. 

代码:

/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
public class Solution {
    public List merge(List intervals) {
        int n = intervals.size();
        int[] starts = new int[n];
        int[] ends = new int[n];
        for(int i = 0; i < n; i++){
            starts[i] = intervals.get(i).start;
            ends[i] = intervals.get(i).end;
        }
        Arrays.sort(starts);
        Arrays.sort(ends);
        List res = new ArrayList();
        for(int i = 0, j = 0; i < n; i++){
            if(i == n - 1 || starts[i+1] > ends[i]){
                res.add(new Interval(starts[j],ends[i]));
                j = i + 1;
            }
        }
        return res;
    }
}

你可能感兴趣的:(#56 Merge Intervals)