AcWing 803. 区间合并
发布日期:2021-05-07 14:08:24 浏览次数:18 分类:原创文章

本文共 1257 字,大约阅读时间需要 4 分钟。

给定 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

输入样例:

51 22 45 67 87 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);                            }}

 

上一篇:AcWing 826. 单链表
下一篇:AcWing 802. 区间和

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2025年03月18日 09时54分04秒