import java.util.*;

/*
 * public class Interval {
 *   int start;
 *   int end;
 *   public Interval(int start, int end) {
 *     this.start = start;
 *     this.end = end;
 *   }
 * }
 */

public class Solution {
    public class ComparaInterval implements Comparator<Interval> {
        @Override
        public int compare(Interval interval1, Interval interval2) {
            if (interval1.start < interval2.start) {
                return -1;
            } else if (interval1.start > interval2.start) {
                return 1;
            } else {
                if (interval1.end < interval2.end) {
                    return -1;
                } else if (interval1.end > interval2.end) {
                    return 1;
                } else {
                    return 0;
                }
            }
        }
    }

    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param Intervals   Interval类一维数组
     * @param newInterval Interval类
     * @return Interval类一维数组
     */
    public Interval[] insertInterval(Interval[] Intervals, Interval newInterval) {
        // write code here

        if (0 == Intervals.length) {
            return new Interval[]{newInterval};
        }

        ArrayList<Interval> arrayList = new ArrayList<>();
        for (Interval interval : Intervals) {
            arrayList.add(interval);
        }
        arrayList.add(newInterval);
        arrayList.sort(new ComparaInterval());

        ArrayList<Interval> res = new ArrayList<>();
        Interval tmpInterval = arrayList.get(0);
        arrayList.remove(0);
        for (Interval interval : arrayList) {
            if (interval.start > tmpInterval.end) {
                res.add(tmpInterval);
                tmpInterval = interval;
            } else {
                if (interval.end <= tmpInterval.end) {

                } else {
                    tmpInterval.end = interval.end;
                }
            }
        }
        res.add(tmpInterval);
        Interval[] intervals = new Interval[res.size()];
        for (int i = 0; i < res.size(); i++) {
            intervals[i] = res.get(i);
        }
        return intervals;
    }
}