leetcode
leetcode 1001 ~ 1050
安排会议日程

安排会议日程

难度:

标签:

题目描述

代码结果

运行时间: 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)

代码细节讲解

🦆
为什么在处理两个时间段列表之前要先对它们进行排序?排序的目的和对算法效率的影响是什么?
在处理两个时间段列表之前进行排序是为了简化时间段交集的查找过程。通过将时间段按开始时间排序,可以确保在遍历时,每个列表中的时间段都是按时间顺序出现。这样,在查找交集时,只需要比较当前两个列表中的时间段。若当前时间段无交集,可以直接移动结束时间较早的时间段的指针,有效地减少了不必要的比较,从而提高算法的效率。排序的时间复杂度为O(n log n),但它为整个查找过程提供了结构上的便利,使得后续的交集查找过程能够以线性时间完成,即O(n)。因此,虽然排序增加了前期的计算成本,但总体上优化了算法的时间效率。
🦆
在寻找两个时间段的交集时,为什么选择移动结束时间较早的时间段的指针?这种选择对算法的效率和结果有什么影响?
选择移动结束时间较早的时间段的指针是为了有效地缩小查找范围,并避免无效的比较。当一个时间段的结束时间较早时,它与其他时间段的可能交集也就结束了。继续比较该时间段已无意义,因此移动其指针到下一个时间段,是一种减少无效操作并加速查找过程的方法。这种选择使算法只在有可能找到有效交集时才进行比较,避免了不必要的比较,从而提高了算法的效率。同时,这种方法保证了算法能够遍历所有可能的时间段组合,确保找到所有可行的交集,不会漏掉任何可能的结果。
🦆
算法如何确保在找到的时间段内确实有至少给定的持续时间(duration)?具体是通过哪些计算和判断实现的?
算法确保找到的时间段内有至少给定的持续时间(duration)是通过计算两个时间段的交集并检查这个交集的长度来实现的。具体操作如下:首先,算法通过取两个时间段的最大开始时间和最小结束时间来确定交集的开始和结束时间。然后,算法计算交集的长度,即结束时间减去开始时间。如果这个长度大于或等于给定的持续时间(duration),那么这个时间段就被认为是有效的,并将其作为结果返回。这种方法通过简单的数学计算确保了时间段的有效性,并且容易实现和理解。

相关问题