1.题目
给定 n n n 个区间 [ l i , r i ] [li,ri] [li,ri],要求合并所有有交集的区间。
注意如果在端点处相交,也算有交集。
输出合并完成后的区间个数。
例如: [ 1 , 3 ] [1,3] [1,3]和 [ 2 , 6 ] [2,6] [2,6]可以合并为一个区间 [ 1 , 6 ] [1,6] [1,6]。
输入格式
第一行包含整数
n
n
n。
接下来 n n n 行,每行包含两个整数 l l l 和 r r r。
输出格式
共一行,包含一个整数,表示合并区间完成后的区间个数。
数据范围
1
≤
n
≤
100000
,
1≤n≤100000,
1≤n≤100000,
− 109 ≤ l i ≤ r i ≤ 109 −109≤li≤ri≤109 −109≤li≤ri≤109
输入样例:
5
1 2
2 4
5 6
7 8
7 9
输出样例:
3
2.基本思想
可以先按左端点排序,再维护一个区间,与后面一个个区间进行 比较。
3.代码实现
import java.util.*;
public class _803区间合并 {
private static int N = 100010;
private static int[] a;
private 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++) {
a = new int[2];
a[0] = sc.nextInt();
a[1] = sc.nextInt();
list.add(a);
}
//将 列表中 每个数组0位置 元素升序排序
list.sort(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0] - o2[0];
}
});
int res = 0;
int r = Integer.MIN_VALUE;//初始化 右端点
for (int[] a : list) {
//判断当前元素的左端点 和 之前区间的 右端点的 大小
if (a[0] > r) res++;//不相交
//更新右端点
r = a[1];
}
System.out.println(res);
}
}