原文链接 华为OD机试统一考试D卷C卷 - 会议室占用时间段(C++ Java JavaScript Python C语言)-CSDN博客
用例
4
1 4
2 5
7 9
14 18
[14 18, 7 9, 1 5]
4
1 4
1 4
2 4
1 9
[1 9]
解题思路
又是区间问题,排序是重点,按结束时间降序排队,然后遍历,看当前的结束时间是否在上一个时间区间内,确定是否是一个新的还是去合并
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
int num =sc.nextInt();
int[][] nums = new int[num][2];
for(int i=0; i< num;i++) {
nums[i][0] = sc.nextInt();
nums[i][1] = sc.nextInt();
}
Arrays.sort(nums, (a,b) -> b[1] -a[1]);//按结束时间降序
List<String> result = new ArrayList<String>();
solution(nums, 1, result); //从第2个开始,第1个默认是开始的比较对象
System.out.println(result);
}
}
public static int solution(int[][] nums, int index, List<String> result){
if(index == nums.length) {//全部处理完毕
result.add(nums[index-1][0] +" "+ nums[index-1][1]);//这是最后一个
return 0;
}
if(nums[index][1] < nums[index-1][0]) { //如果我的结束小于上一个的开始,则认为是一个新时间段
result.add(nums[index-1][0] +" "+ nums[index-1][1]);
}else {//每次都把区间合并的结果更新到当前索引,节省存储空间
nums[index][0] = Math.min(nums[index-1][0], nums[index][0]);
nums[index][1] = nums[index-1][1];
}
return solution(nums, index+1, result);
}