Java 区间合并

区间合并

1.将所有区间按照左端点从小到大排序,这里使用的是List接口里的sort方法,并重写排序规则
2.每两个区间有三种状态:完全包含、部分包含、不包含,如果是不包含就res++,另外两种就取右端点大的数为标记点

【例题:】
给定 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

【代码:】

import java.io.*;
import java.util.*;

public class Main {

    static List<int[]> f = new ArrayList<>();

    public static void main(String[] args) throws IOException{
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(read.readLine());
        for(int i = 1; i <= n; i++) {
            String[] str = read.readLine().split(" ");
            int[] t = {Integer.parseInt(str[0]),Integer.parseInt(str[1])};
            f.add(t);
        }
        f.sort(new Comparator<int[]>(){
            public int compare(int[] o1, int[] o2){
                return o1[0] - o2[0];
            }
        });
        int ed = Integer.MIN_VALUE, res = 0;
        for (int[] t : f) {
            if(t[0] > ed) res ++;
            ed = Math.max(ed, t[1]);
        }
        System.out.println(res);
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Oak Coffee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值