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) {
        ArrayList<Interval> res = new ArrayList<>();
        //边际条件
        if(intervals.size() == 0){
            return res;
        }
        //重载比较器,来对区间进行排序
        Collections.sort(intervals,new Comparator<Interval>(){
          public int compare(Interval i1,Interval i2){
              if(i1.start != i2.start){
                  return i1.start - i2.start;
              }else{
                  return i1.end - i2.end;
              }
          }  
        });
        //结果中加入首区间
        res.add(intervals.get(0));
        int flag = 0;
        //遍历后面的区间进行合并比对
        for(int i = 1;i<intervals.size();i++){
            Interval x = res.get(flag);
            Interval y = intervals.get(i);
            if(x.end < y.start){
                res.add(y);
                flag++;
            }else{
                res.remove(flag);
                Interval rm = new Interval(x.start,y.end);
              //当后一个区间被前一个区间包裹时
                if(x.end > y.end){
                    rm.end = x.end;
                }
                res.add(rm);
            }
        }
        return res;    
    }
}