LeetCode-57. 插入区间-Java-medium

题目链接

法一

    /**
     * 时间复杂度:O(n)
     *
     * @param intervals
     * @param newInterval
     * @return
     */
    public int[][] insert(int[][] intervals, int[] newInterval) {
        List<int[]> merge = new ArrayList<>();
        int index = 0;
        while (index < intervals.length && intervals[index][1] < newInterval[0]) { // intervals[index]第2维 < newInterval第1维
            merge.add(intervals[index++]);
        }
        while (index < intervals.length && intervals[index][0] <= newInterval[1]) { // intervals[index]第1维 <= newInterval第2维
            newInterval[0] = Math.min(intervals[index][0], newInterval[0]); // 需合并两区间的最左边
            newInterval[1] = Math.max(intervals[index][1], newInterval[1]); // 需合并两区间的最右边
            index++;
        }
        merge.add(newInterval);
        while (index < intervals.length) {
            merge.add(intervals[index++]);
        }
        return merge.toArray(new int[0][]);
    }

本地测试

        /**
         * 57. 插入区间
         */
        lay.showTitle(57);
        Solution57 sol57 = new Solution57();
        int[][] intervals57 = new int[][]{{1, 3}, {6, 9}};
        int[] newInterval57 = new int[]{2, 5};
        arrayOpt.showIntTwoDimArray(intervals57, intervals57.length);
        int[][] ans57 = sol57.insert(intervals57, newInterval57);
        arrayOpt.showIntTwoDimArray(ans57, ans57.length);

你可能感兴趣的:(#,矩阵,java,leetcode,算法)