【算法】区间合并
区间合并
给定 n 个区间[li,ri],要求合并所有有交集的区间。
注意如果在端点处相交,也算有交集。
输出合并完成后的区间个数。
例如:[1,3] 和 [2,6] 可以合并为一个区间 [1,6]。
输入格式
第一行包含整数 n。
接下来 n 行,每行包含两个整数 l 和 r。
输出格式
共一行,包含一个整数,表示合并区间完成后的区间个数。
数据范围
1≤n≤100000
−
1
0
9
−10^9
−109≤li≤ri≤
1
0
9
10^9
109
输入样例:
5
1 2
2 4
5 6
7 8
7 9
输出样例:
3
思路分析
1、按照区间左边界排序,排序后维护一个区间为当前区间,之后的区间与当前维护的区间一共有三种情况、分别是
如果是第一种维护区间不做处理、第二种修改维护区间的右边界值、第三种将比较区间作为新的维护区间且计数器+1
因为第一步已经做了排序,因此并不会出现比较区间左边界在维护区间左边界左边的情况
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<int[]> boundary = new ArrayList<>();
for (int i = 0; i < n; i++) {
int left = sc.nextInt();
int right = sc.nextInt();
boundary.add(new int[]{left, right});
}
//按照左边界排序
Collections.sort(boundary, Comparator.comparingInt(a -> a[0]));
int myL = boundary.get(0)[0];
int myR = boundary.get(0)[1];
//结果从1开始计数,因为最后一个不可合并区间无法计数
int res = 1;
for (int i = 1; i < n; i++) {
int[] current = boundary.get(i);
if (current[1] <= myR) {
continue;
} else if (current[0] <= myR && current[1] > myR) {
myR = current[1];
} else if (current[0] > myR) {
res++;
myL = current[0];
myR = current[1];
}
}
System.out.println(res);
sc.close();
}
}