0057. Insert Intervals (H)

Insert Interval (H)

題目

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).java

You may assume that the intervals were initially sorted according to their start times.數組

Example 1:app

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2:code

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

題意

給定一個左端點遞增且互不重疊的區間數組,向其中插入一個新的區間,若有重疊則須要合併,返回處理後的區間數組。it

思路

先將全部右端點在新區間左端點以前的區間(即必定不會相加)插入到結果中,再將全部能夠與新區間合併的區間進行合併,並加入到結果中,最後將剩餘一部分不會合並的區間加入到結果中。io


代碼實現

Java

class Solution {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        List<int[]> list = new ArrayList<>();
        int i = 0;
        while (i < intervals.length && intervals[i][1] < newInterval[0]) {
            list.add(intervals[i++]);
        }
        while (i < intervals.length && intervals[i][0] <= newInterval[1] && intervals[i][1] >= newInterval[0]) {
            newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
            newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
            i++;
        }
        list.add(newInterval);
        while (i < intervals.length) {
            list.add(intervals[i++]);
        }

        return list.toArray(new int[0][]);
    }
}
相關文章
相關標籤/搜索