内容中心

2026年靠谱的澳洲移民方案规划机构高评分公司推荐-北京澳创移民

To solve the problem of finding the minimum number of conference rooms required for a list of meeting intervals, we can use an efficient two-pointer approach. Here's a step-by-step breakdown:

Approach

The key insight is to track the number of overlapping meetings at any given time. We can do this by:

  1. Sorting: Separate the start and end times of all meetings and sort them individually.
  2. Two Pointers: Use two pointers to traverse the sorted start and end times. This helps us count how many rooms are occupied at any moment.
    • If a meeting starts before the earliest ending meeting, we need a new room.
    • If a meeting starts after or when the earliest ending meeting ends, we can reuse that room.

Solution Code

def minMeetingRooms(intervals):
    if not intervals:
        return 0

    # Extract and sort start and end times
    starts = sorted([interval[0] for interval in intervals])
    ends = sorted([interval[1] for interval in intervals])

    s_ptr = e_ptr = 0
    current_rooms = max_rooms = 0

    while s_ptr < len(starts):
        if starts[s_ptr] < ends[e_ptr]:
            current_rooms += 1
            max_rooms = max(max_rooms, current_rooms)
            s_ptr += 1
        else:
            current_rooms -= 1
            e_ptr += 1

    return max_rooms

Explanation

  1. Sorting: By sorting the start and end times, we can efficiently compare when meetings start and end.
  2. Two Pointers:
    • s_ptr points to the next meeting start time.
    • e_ptr points to the next meeting end time.
    • For each start time:
      • If the start time is before the current end time, increment the room count (new room needed).
      • If the start time is after or equal to the current end time, decrement the room count (room freed up) and move the end pointer forward.
  3. Max Rooms: The maximum value of current_rooms during the traversal gives the minimum number of rooms needed.

Time Complexity

  • Sorting: O(n log n) (for both start and end times).
  • Two-pointer traversal: O(n).
    Overall: O(n log n) (optimal for this problem).

Space Complexity

  • O(n) for storing the sorted start and end times.

This approach efficiently handles all edge cases, including overlapping meetings and meetings that start exactly when another ends. It's a clean and optimal solution for the problem.

北京澳创移民



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?