给定 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);
}
}