56. Merge Intervals

思路

首先要注意的是,所给的 interval 数组是无序的。解法一要先将数组按左边界大小排序。新建一个空 List 存储所有 merge 后的 intervals。然后遍历排序好的数组,如果其中的 interval 和 list 中最后一个 interval 有重合区域,将 list 中的这个 interval 扩展。如果包含在内,则不发生变化。 如果没有重合区域,就将这个新的 interval 添加进 list 中。

解法一

/*
Sort the intervals according to their start value;
Initialize a list newInterval to store result intervals;
Set the first value of the list to be the first element newInterval in the sorted interval array.
for (intervals[0], intervals[1], ... ,intervals[n - 1])
    // If overlap, set the larger end to be the end for newInterval;
    if (intervals[i][0] >= newInterval[0])
        end of last result interval = max(intervals[i][1], newInterval[1]);
    else
        newInterval = intervals[i];
        add(newInterval);
    endif
    return the result interval;
*/
class Solution {
    public int[][] merge(int[][] intervals) {
        // return the original array if its length <= 1
        if (intervals.length <= 1) {
            return intervals;
        }
        Arrays.sort(intervals,(i1, i2)->Integer.compare(i1[0], i2[0])); // O(nlogn)
        List<int[]> result = new ArrayList<>();
        int[] newInterval = intervals[0];
        result.add(newInterval);
        for (int[] interval : intervals) {
            // Overlap
            if (interval[0] <= newInterval[1]) {
                // Update the end of the last interval in the result
                result.get(result.size() - 1)[1] = Math.max(interval[1], newInterval[1]);
            }
            // Not overlap, just add the interval to the result.
            else {
                newInterval = interval;
                result.add(newInterval);
            }
        }
        return result.toArray(new int[result.size()][2]);
    }
}

解法二

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!