LeetCode 2073 Time Needed to Buy Tickets
<div>
There are n people in a line queuing to buy tickets, where the 0<sup>th</sup> person is at the front of the line and the (n - 1)<sup>th</sup> person is at the back of the line.
You are given a 0-indexed integer array tickets of length n where the number of tickets that the i<sup>th</sup> person would like to buy is tickets[i].
Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line.
Return the time taken for the person at position k**(0-indexed) **to finish buying tickets.
Example 1:
<pre>Input: tickets = [2,3,2], k = 2 Output: 6 Explanation:
- In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1].
- In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0]. The person at position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds. </pre>
Example 2:
<pre>Input: tickets = [5,1,1,1], k = 0 Output: 8 Explanation:
- In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0].
- In the next 4 passes, only the person in position 0 is buying tickets. The person at position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds. </pre>
Constraints:
n == tickets.length1 <= n <= 1001 <= tickets[i] <= 1000 <= k < n
</div>
题目大意:
排队买票,每个人都有不同的票数需求。每人每次只能买一张,买完后重新排队。买一张票需要1秒,求第k个人买票的总时间。
解题思路:
一开始按照题目要求老老实实每个元素减一,按照流程计算,但效率较低。考虑若所有人票数大于0,每轮计算结果是一样的:
当前排队人数乘以排队的人中的最小票数。当最小票数人离队后,公式会改变。如此循环直到第k个人票数也变成0为止。
解题步骤:
- 求最小值
- 计算票数
- 更新人数,继续循环
- 结果减去排在第k个人后的人数
注意事项:
- 结果要减去排在第k个人后的还在排队的人数(tickets数不为负数,可以等于0,因为是同时在同一轮买到足够票)。
Python代码:
1
2
3
4
5
6
7
8
9
10def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
sum, ppl, min_tickets = 0, len(tickets), 0
while tickets[k] > 0:
min_tickets = min(t for t in tickets if t > 0)
sum += min_tickets * ppl
tickets = [t - min_tickets for t in tickets]
ppl -= tickets.count(0)
after_k = [i for i in range(k + 1, len(tickets)) if tickets[i] >= 0]
return sum - len(after_k)
算法分析:
时间复杂度为O(n),空间复杂度O(1)。


