Leetcode(java) 56. Merge Intervals

本文介绍了一种有效的合并区间算法,该算法将输入的一系列区间进行合并,并返回一系列不重叠的区间。通过排序和列表操作,可以高效地解决区间合并问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Q:

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

A:

Use list to add intervals

if the current interval overlaps the previous interval, merge this two intervals.

Otherwise, add the interval to the list directly.

Finally, convert the list to Array.

class Solution {
    public int[][] merge(int[][] intervals) {
      
        if(intervals.length==0) return new int[0][2];

        Arrays.sort(intervals, new Comparator<int[]>(){
            public int compare(int[] a, int[] b){
                return a[0]-b[0];
            }
        }
        
        );

        List<int[]> list = new ArrayList<int[]>();
        list.add(intervals[0]);
        for(int[] i :intervals){
            if(i[0]<=list.get(list.size()-1)[1]){
                list.get(list.size()-1)[1] = Math.max(list.get(list.size()-1)[1], i[1]);
            }else{
                list.add(i);
            }
        }

        return list.toArray(new int[list.size()][2]);

    }

   
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值