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& tickets, int k) {
    int n=tickets.size();
    int totalTime=0;
    queueq;
    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;
    }
    };

相关推荐
ShineWinsu2 小时前
对于 C++:C++14中从变量模板、泛型 Lambda 到并发与字面量的解析
c++·算法
土司大王2 小时前
LeetCode hot100——合并两个有序链表
算法·leetcode·链表
码行山野赴时序归途3 小时前
算法效率的度量(上):时间复杂度中的对数思维
c语言·数据结构·算法
算AI3 小时前
基于LLM的无人机仿真测试:新方法竞赛夺佳绩
人工智能·深度学习·算法·机器学习·ai
kaixin_啊啊4 小时前
专用优化算法LKH
算法
一木 之林5 小时前
四、STL容器与数据结构
开发语言·数据结构·c++
_Narcissus_6 小时前
二分算法笔记及例题
数据结构·c++·笔记·算法·蓝桥杯·查找·二分算法
tachibana26 小时前
RAGAS 指标解读
数据库·人工智能·算法·机器学习·架构·大模型·llm
qq_419563096 小时前
ToT 的 BFS/DFS 有个致命缺口:蒙特卡洛树搜索(MCTS)用「随机试错+统计」让大模型想得更深,小模型 + 它竟超过 GPT-4
算法·深度优先·宽度优先
万法若空7 小时前
CSP-J/S 排序算法完整专题训练题单
数据结构·算法·排序算法