📅  最后修改于: 2023-12-03 14:58:31.101000             🧑  作者: Mango
Given a list of activities which contain start time, end time, and the room number in which it will take place, there are n
activities in total. Two activities can happen in the same room at the same time. The task is to find the minimum number of rooms required such that all the activities can take place without any overlap.
This problem can be solved by sorting the activities according to their start times and then traversing the list of activities, keeping track of the rooms in which the activities are taking place. If the current activity starts after the previous activity ends, then the same room can be used, otherwise a new room needs to be allocated. The number of rooms needed will be the maximum number of rooms occupied at any point in time.
The time complexity of the algorithm is O(nlogn), where n is the number of activities, due to the sorting step. The space complexity is also O(n), as in the worst case scenario, each activity would need its own room.
def min_rooms(activities):
activities.sort(key=lambda x: x[0]) # Sort by start time
rooms = []
for activity in activities:
allocated = False
for room in rooms:
if activity[0] >= room[-1][1]:
# Allocate to existing room
room.append(activity)
allocated = True
break
if not allocated:
# Allocate to new room
rooms.append([activity])
return len(rooms)
This problem can be solved by sorting the activities and then traversing the list of activities to keep track of the rooms that are occupied. The time complexity of the algorithm is O(nlogn) due to the sorting step.