[LeetCode] 2073. Time Needed to Buy Tickets

CNoodle發表於2024-04-10

There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th 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 ith 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:
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.

Example 2:
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.

Constraints:
n == tickets.length
1 <= n <= 100
1 <= tickets[i] <= 100
0 <= k < n

買票需要的時間。

有 n 個人前來排隊買票,其中第 0 人站在隊伍 最前方 ,第 (n - 1) 人站在隊伍 最後方 。

給你一個下標從 0 開始的整數陣列 tickets ,陣列長度為 n ,其中第 i 人想要購買的票數為 tickets[i] 。

每個人買票都需要用掉 恰好 1 秒 。一個人 一次只能買一張票 ,如果需要購買更多票,他必須走到 隊尾 重新排隊(瞬間 發生,不計時間)。如果一個人沒有剩下需要買的票,那他將會 離開 隊伍。

返回位於位置 k(下標從 0 開始)的人完成買票需要的時間(以秒為單位)。

思路

這道題的暴力解是用一個佇列,把所有人需要購買的票數放進去,然後開始遍歷每一個元素。但是如果人數太多(n 太大)就一定會超時。

這裡我提供一個次優解,不需要用佇列,就是簡單的模擬。當第 k 個人還未完成購票的時候,就一直遍歷整個 input 陣列。因為每個人一次只能購買一張票,一次購買的動作耗時一秒鐘,所以我們一直遍歷整個陣列直到第 k 個人完成購票,才把迴圈 break,返回結果。

這裡同時我提供一個網上看到的最優解,時間複雜度為O(n),但是很難想到。

複雜度

時間O(n * k)
空間O(1)

程式碼

Java實現

class Solution {
    public int timeRequiredToBuy(int[] tickets, int k) {
		int n = tickets.length;
		int time = 0;
		while (tickets[k] > 0) {
			for (int i = 0; i < n; i++) {
				if (tickets[i] > 0) {
					tickets[i]--;
					time++;
					if (i == k && tickets[k] == 0) {
						return time;
					}
				}
			}
		}
		return time;
    }
}

相關文章