区间合并问题


什么是区间合并问题?
区间合并就是快速将有交集的区间合并,可以通过这道题来理解一下!!!

区间合并问题

给定 n 个区间 [li,ri],要求合并所有有交集的区间。

注意如果在端点处相交,也算有交集。

输出合并完成后的区间个数。

例如:[1,3]和[2,6]可以合并为一个区间[1,6]。

输入格式
第一行包含整数n。

接下来n行,每行包含两个整数 l 和 r。

输出格式
共一行,包含一个整数,表示合并区间完成后的区间个数。

数据范围
1≤n≤100000,
−109≤li≤ri≤109
输入样例:
5
1 2
2 4
5 6
7 8
7 9
输出样例:
3

做法:

  1. 按区间的左端点排序
  2. 扫描区间,将可能的区间进行合并
  3. 一共有四种情况:
  • 比当前区间小
  • 和当前区间相同
  • 和当前去区间有交集
  • 和当前区间无交集

解法一:合并区间后求个数

import java.util.*;
class Main{
    static int [] nums;
    static ArrayList<int[]> list = new ArrayList<>();
    public static void main(String [] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for(int i =0;i<n;i++){
            nums = new int[2];
            nums[0] = sc.nextInt();
            nums[1] = sc.nextInt();
            list.add(nums);
        }
        list.sort(new Comparator<int []>(){
             @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
      System.out.println(merge(list));
        
    }
    static int merge(ArrayList<int[]> list){
        ArrayList<int []>res = new ArrayList<>();
        int l = Integer.MIN_VALUE;
        int r = Integer.MIN_VALUE;
        for (int[] a : list) {
            //下一个区间左端点大于老区间右端点
            if (a[0] > r){
                //找到了新区间,就将老区间添加(不直接加新区间,因为新区间右端点还没确定)
                if (l != Integer.MIN_VALUE){
                    res.add(new int[]{l,r});
                }
                l = a[0];
                r = a[1];
            }else {
                r = Math.max(r, a[1]);
            }
        }
        //最后一个合并区间,判断条件防止list为空
        if (l != Integer.MIN_VALUE){
            res.add(new int[]{l,r});
        }
        return res.size();
    }
        
    }

做法二: 统计个数

还有一种,计算个数的方法 没有合并

import java.util.*;
class Main{
    public static void main(String [] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int [][]nums = new int[n][2];
        for(int i =0;i<n;i++){
            nums[i][0] = sc.nextInt();
            nums[i][1] = sc.nextInt();
        }
        Arrays.sort(nums,(o1,o2) ->{
            return o1[0]-o2[0];
        });
        int res = 1;
        int maxr = nums[0][1];
        for(int i =1;i<n;i++){
            if(nums[i][0]<=maxr){
                maxr = Math.max(maxr,nums[i][1]);
            }else{
                res++;
                maxr = nums[i][1];
            }
        }
        System.out.println(res);
        
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值