[LeetCode] 56. 合并区间

yi开始想到用栈,但是好像不是很好的方法哈。。。。。

害,真的脑子笨就要多刷题总结咯。。

先排序再合并

class Solution {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (v1, v2) -> v1[0] - v2[0]);
        int[][] res = new int[intervals.length][2];
        int index=-1;
        for(int[] interval:intervals){
            if(index==-1||interval[0]>res[index][1]){
                res[++index]=interval;
            }else{
                res[index][1]=Math.max(interval[1],res[index][1]);
            }
        }
        return Arrays.copyOf(res,index+1);
    }
}

 看到高分答案还有一个用快排的,牛啊。。。。下次来看!

原文地址:https://www.cnblogs.com/doyi111/p/12717029.html