57. Insert Interval

Back to Homepage   |     Back to Code List


class Solution {
    public static List<Interval> insert1(List<Interval> intervals,
         Interval newInterval) {
        List<Interval> res = new ArrayList<>();

        for (Interval interval: intervals) {
            // new.start > interval.end
            if (newInterval == null || newInterval.start > interval.end) {
                res.add(interval);
            } else if (newInterval.end < interval.start) {
                // new.end < interval.start
                res.add(newInterval);
                res.add(interval);
                newInterval = null;
            } else {
                newInterval.start = Math.min(newInterval.start,
                 interval.start);
                newInterval.end = Math.max(newInterval.end,
                 interval.end);
            }
        }

        if (newInterval != null) res.add(newInterval);

        return res;
    }
}