区间合并
1.将所有区间按照左端点从小到大排序,这里使用的是List接口里的sort方法,并重写排序规则
2.每两个区间有三种状态:完全包含、部分包含、不包含,如果是不包含就res++,另外两种就取右端点大的数为标记点
【例题:】
给定 n 个区间 [li,ri],要求合并所有有交集的区间。
注意如果在端点处相交,也算有交集。
输出合并完成后的区间个数。
例如:[1,3]和[2,6]可以合并为一个区间[1,6]。
输入格式
第一行包含整数n。
接下来n行,每行包含两个整数 l 和 r。
输出格式
共一行,包含一个整数,表示合并区间完成后的区间个数。
数据范围
1≤n≤100000,
−109≤li≤ri≤109
输入样例:
5
1 2
2 4
5 6
7 8
7 9
输出样例:
3
【代码:】
import java.io.*;
import java.util.*;
public class Main {
static List<int[]> f = new ArrayList<>();
public static void main(String[] args) throws IOException{
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(read.readLine());
for(int i = 1; i <= n; i++) {
String[] str = read.readLine().split(" ");
int[] t = {Integer.parseInt(str[0]),Integer.parseInt(str[1])};
f.add(t);
}
f.sort(new Comparator<int[]>(){
public int compare(int[] o1, int[] o2){
return o1[0] - o2[0];
}
});
int ed = Integer.MIN_VALUE, res = 0;
for (int[] t : f) {
if(t[0] > ed) res ++;
ed = Math.max(ed, t[1]);
}
System.out.println(res);
}
}