安排会议日程
难度:
标签:
题目描述
代码结果
运行时间: 50 ms, 内存: 22.0 MB
/*
* Leetcode 1229: Meeting Scheduler using Java Streams
* Given the availability time slots arrays slots1 and slots2 of two people and a meeting duration,
* return the earliest time slot that works for both of them and is of duration duration.
* If there is no common time slot that satisfies the duration requirement, return an empty array.
*
* Approach:
* 1. Convert slots1 and slots2 into sorted lists of int arrays.
* 2. Use nested streams to find the earliest overlapping slot with the required duration.
* 3. If a suitable time slot is found, return the start time and start time + duration as a list.
* 4. If no suitable time slot is found, return an empty list.
*/
import java.util.*;
import java.util.stream.*;
public class MeetingSchedulerStream {
public List<Integer> minAvailableDuration(int[][] slots1, int[][] slots2, int duration) {
List<int[]> list1 = Arrays.stream(slots1).sorted(Comparator.comparingInt(a -> a[0])).collect(Collectors.toList());
List<int[]> list2 = Arrays.stream(slots2).sorted(Comparator.comparingInt(a -> a[0])).collect(Collectors.toList());
return list1.stream()
.flatMap(slot1 -> list2.stream()
.map(slot2 -> new int[] { Math.max(slot1[0], slot2[0]), Math.min(slot1[1], slot2[1]) })
.filter(interval -> interval[1] - interval[0] >= duration)
.findFirst()
.stream())
.map(interval -> Arrays.asList(interval[0], interval[0] + duration))
.findFirst()
.orElse(Collections.emptyList());
}
}
解释
方法:
本题解的核心思路是找出两个时间段列表中的共同空闲时间,并确保这段时间至少有给定的持续时间(duration)。首先,通过排序两个时间段列表以便按时间顺序处理。使用两个指针分别遍历两个列表,寻找两个时间段的交集。如果交集的长度至少为duration,则返回该时间段的开始和结束时间。如果当前比较的两个时间段没有足够的交集或者一个时间段比另一个早结束,则移动结束时间较早的时间段的指针,继续寻找可能的交集。如果遍历完毕后仍无合适时间段,则返回空列表。
时间复杂度:
O(n log n)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么在处理两个时间段列表之前要先对它们进行排序?排序的目的和对算法效率的影响是什么?
▷🦆
在寻找两个时间段的交集时,为什么选择移动结束时间较早的时间段的指针?这种选择对算法的效率和结果有什么影响?
▷🦆
算法如何确保在找到的时间段内确实有至少给定的持续时间(duration)?具体是通过哪些计算和判断实现的?
▷