2073. Time Needed to Buy Tickets

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 leavethe 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

    class Solution {
    public:
    int timeRequiredToBuy(vector<int>& tickets, int k) {
    int n=tickets.size();
    int totalTime=0;
    queue<int>q;
    for(int i=0;i<n;i++){
    q.push(i);
    }
    while(!q.empty() && tickets[q.front()]>0){
    int currentPerson=q.front();
    q.pop();
    tickets[currentPerson]--;
    totalTime++;
    if(tickets[currentPerson]){
    q.push(currentPerson);
    }
    if(currentPerson==k && tickets[currentPerson]==0){
    return totalTime;
    }
    }
    return totalTime;
    }
    };

相关推荐
逆水寻舟10 分钟前
算法学习记录2
python·学习·算法
羞儿12 分钟前
【读点论文】基于二维伽马函数的光照不均匀图像自适应校正算法
人工智能·算法·计算机视觉
续亮~1 小时前
6、Redis系统-数据结构-03-压缩列表
数据结构·数据库·redis
青衫酒1451 小时前
中国剩余定理
算法
鸽鸽程序猿1 小时前
【数据结构】顺序表
java·开发语言·数据结构·学习·算法·intellij idea
Chris-zz2 小时前
C++:继承
开发语言·c++·算法·学习方法
硕风和炜2 小时前
【LeetCode:3033. 修改矩阵 + 模拟】
java·算法·leetcode·矩阵·模拟
取加若则_2 小时前
C++入门(C语言过渡)
c语言·开发语言·数据结构·c++·算法
真果粒wrdms3 小时前
【在线词典】项目实现
linux·c语言·嵌入式硬件·算法·udp·sqlite3
YangZheng@3 小时前
23种设计模式
c++·算法·设计模式