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:
- Sorting: Separate the start and end times of all meetings and sort them individually.
- 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
- Sorting: By sorting the start and end times, we can efficiently compare when meetings start and end.
- Two Pointers:
s_ptrpoints to the next meeting start time.e_ptrpoints 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.
- Max Rooms: The maximum value of
current_roomsduring 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.

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