算法基础-区间合并

1、按照区间的左端点排序
2、

左端点小于等于ed,只需要更新ed和右端点的最大值

左端点大于ed,存入res中,并更新st和ed,最后一组数据手动插入res

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        List<int[]> seg = new ArrayList<>();
        List<int[]> res = new ArrayList<>();
        int n = in.nextInt();
        while(n -- > 0) {
            int l = in.nextInt();
            int r = in.nextInt();
            seg.add(new int[] {l, r});
        }
        seg.sort((a,b) -> {
            if(a[0] != b[0])
                return Integer.compare(a[0], b[0]);
            else
                return Integer.compare(a[1], b[1]);
        });
        int st = -2000000000;
        int ed = -2000000000;
        for (int[] item : seg) {
            //如果进来的这个区间左端点大于当前区间的右端点
            if(item[0] > ed) {
                //第一组数字不会添加到res
                if(st != -2000000000)
                    res.add(new int[] {st, ed});
                st = item[0];
                ed = item[1];
            } else {
                //如果进来的这个区间右端点小于等于当前区间的右端点
                ed = Math.max(ed, item[1]);
            }
        }
        //最后一组数据只更新了st、ed,并没有添加到res
        if (st != -2000000000) {
            res.add(new int[]{st, ed});
        }
        System.out.println(res.size());
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值