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 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

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