Re: [闲聊] 每日leetcode

楼主: dont   2024-10-11 10:39:45
1942. The Number of the Smallest Unoccupied Chair
## 思路
先把times转成 (start/end time, event_state, idx) 的time_heap
照时间顺序检查
如果state是-1, 就释出椅子到min heap (free_chairs)
如果state是1, 就从free_chairs拿最小的椅子或是拿一张新椅子
## Code
```python
class Solution:
def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:
time_heap = []
for idx, (start, end) in enumerate(times):
heapq.heappush(time_heap, (start, 1, idx))
heapq.heappush(time_heap, (end, -1, idx))
free_chairs = []
chair_mapping = {}
max_idx = 0
while time_heap:
time, state, idx = heapq.heappop(time_heap)
if state == -1:
chair_idx = chair_mapping[idx]
heapq.heappush(free_chairs, chair_idx)
continue
if free_chairs:
chair_idx = heapq.heappop(free_chairs)
else:
chair_idx = max_idx
max_idx += 1
if idx == targetFriend:
return chair_idx
chair_mapping[idx] = chair_idx
return -1
```

Links booklink

Contact Us: admin [ a t ] ucptt.com