public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
        // Start typing your Java solution below
        // DO NOT write main() function

        if (intervals == null || intervals.size() == 0 || intervals.size() == 1) {
            return intervals;
        }
        IntervalComparator ic = new IntervalComparator();
        Collections.sort(intervals, ic);
        ArrayList<Interval> result = new ArrayList<Interval>();
        int head = intervals.get(0).start;
        int tail = intervals.get(0).end;
        for (int i = 1; i < intervals.size(); i++) {
            if (intervals.get(i).start <= tail) {
                tail = Math.max(tail, intervals.get(i).end);
            } else {
                result.add(new Interval(head, tail));
                head = intervals.get(i).start;
                tail = intervals.get(i).end;
            }
        }
        result.add(new Interval(head, tail));

        return result;
    }