[Leetcode] 56. Merge Intervals

来源:互联网 发布:wubi安装ubuntu 编辑:程序博客网 时间:2024/05/02 03:59

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; } * } */import java.util.ArrayList;public class Solution {    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {        if(intervals == null || intervals.size() <= 1) return intervals;        ArrayList<Interval> result = new ArrayList<Interval>();        Collections.sort(intervals, new IntervalComparator());        Interval last = intervals.get(0);        for(int i = 1; i < intervals.size(); i++){            Interval current = intervals.get(i);            if(current.start <= last.end){                last.end = Math.max(current.end, last.end);            } else {                result.add(last);                last = current;            }        }        result.add(last);        return result;    }    private class IntervalComparator implements Comparator<Interval>{        public int compare(Interval a, Interval b){            return a.start - b.start;        }    }}



0 0