AcWing 803. 区间合并

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

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

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

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

输入格式

第一行包含整数n。

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

输出格式

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

数据范围

1≤n≤1000001≤n≤100000,
−109≤li≤ri≤109−109≤li≤ri≤109

输入样例:

5
1 2
2 4
5 6
7 8
7 9

输出样例:

3
//右区间值大,就合并,然后更新右值
import java.io.*;
import java.lang.Integer;
import java.util.*;
class Node{
    int first;
    int second;
    public Node(int first, int second){
        this.first = first;
        this.second = second;
    }
}
class Main{
    public static void main(String[] args)throws Exception{
        BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.valueOf(buf.readLine());
        Node[] nodes = new Node[n];
        for(int i = 0; i < n; ++i){
            String[] params = buf.readLine().split(" ");
            int x = Integer.valueOf(params[0]);
            int y = Integer.valueOf(params[1]);
            nodes[i] = new Node(x, y);
        }
        Arrays.sort(nodes, (p,q)->{return p.second - p.first;});
        int cnt = 0;
        int max = -100010; 
        for(int i = 0; i < n; ++i){
            if(max < nodes[i].first)cnt++;
            max = Math.max(max, nodes[i].second);
        }
        System.out.printf("%d", cnt);
        
        
        
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值