57. Insert Interval

题目链接:https://leetcode.com/problems...

public class Solution {
    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
        // skip intervals which not overlap with new one 
        // intervals.get(i).end < newInterval.start
        List<Interval> res = new ArrayList();
        int i = 0, n = intervals.size();
        while(i < n && intervals.get(i).end < newInterval.start) res.add(intervals.get(i++));
        // merge the overlap part
        // intervals.get(i).start <= newInterval.end
        while(i < n && intervals.get(i).start <= newInterval.end) {
            newInterval.start = Math.min(newInterval.start, intervals.get(i).start);
            newInterval.end = Math.max(newInterval.end, intervals.get(i).end);
            i++;
        }
        res.add(newInterval);
        // add last intervals without overlap with new one
        while(i < n) res.add(intervals.get(i++));
        
        return res;
    }
}

lulouch13
13 声望6 粉丝