题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是给一个数组,代表一群人到达和离开的时间,人一旦到达就会占据目前下标最小的座位,求名单第一个人占据到的座位下标。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:
targetTime = times[targetFriend][0]
min_seat = -1
free_seat = []
heapq.heapify(free_seat)
seated = []
heapq.heapify(seated)
times.sort(key=lambda x : x[0])

for time in times:
while seated and seated[0][0] <= time[0]:
free = heapq.heappop(seated)
heapq.heappush(free_seat, free[1])

if free_seat:
nxt_seat = heapq.heappop(free_seat)
else:
min_seat += 1
nxt_seat = min_seat

if targetTime == time[0]:
# print(targetTime)
# print(time)
# print(seated)
# print(free_seat)
return nxt_seat
heapq.heappush(seated, (time[1], nxt_seat))