代码参考作者轻叶的打卡记录, 自己补充相关注释
代码
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
// 对读入数据进行初始化
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(cin.readLine()); // 读取一行数据
// nums[0]存放区间左端点, nums[1]存放区间右端点
int nums[][] = new int[n][2];
for (int i = 0; i < n; i++) {
String[] strs = cin.readLine().split(" ");
nums[i][0] = Integer.parseInt(strs[0]);
nums[i][1] = Integer.parseInt(strs[1]);
}
// 通过左端点进行排序
Arrays.sort(nums, new Comparator<int[]>() {
public int compare(int[] o1, int[] o2) {
return o1[0] - o2[0];
}
});
int end = Integer.MIN_VALUE; // 题目中给出 r的取值范围, 初始化为最小的数
int sum = 0;
// 从第二个区间开始循环判断
for (int st = 1; st < n; st++) {
// 如果本轮区间左端点的下标 > 前一个区间的右端点的下标, 表示两个区间无法连接
if (nums[st][0] > end)
sum++; // 合并后区间个数 +1
end = Math.max(end, nums[st][1]); // 更新 end为最大值
}
// 输出结果
System.out.println(sum);
}
}