import java.util.*;
/**
 * 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 ArrayList<Interval> merge(ArrayList<Interval> intervals) {
        if (intervals == null || intervals.size() < 2) {
            return intervals;
        }
        Collections.sort(intervals, (a ,b) -> a.start - b.start);
        ArrayList<Interval> res = new ArrayList<>();
        res.add(intervals.get(0));
        for (int i = 1; i < intervals.size(); i++) {
            Interval pre = res.get(res.size() - 1);
            Interval cur = intervals.get(i);
            if (pre.end < cur.start) {
                res.add(cur);
            }  else {
                Interval merged = new Interval(pre.start, Math.max(pre.end, cur.end));
                res.remove(res.size() - 1);
                res.add(merged);
            }
        }
        return res;
    } 
}