Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode题解:2073. 买票需要的时间,模拟,JavaScript,详细注释 #468

Open
chencl1986 opened this issue Jul 24, 2024 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:
https://leetcode.cn/problems/time-needed-to-buy-tickets/

解题思路:

  1. 根据题意,只要tickets[k] > 0,就可以不断排队购票
  2. 因此不断循环,直到tickets[k]为0停止
  3. 每次循环都将tickets中的每个人购票次数减1,同时将购票时间加1
  4. 如果遇到tickets[k]1,则进行最后一次购票,并返回结果
/**
 * @param {number[]} tickets
 * @param {number} k
 * @return {number}
 */
var timeRequiredToBuy = function(tickets, k) {
  let result = 0 // 存储结果

  // 不断循环直到tickets[k]为0,表示购买到所需数量的票
  while (tickets[k]) {
    // 每次循环tickets
    for (let i = 0; i < tickets.length; i++) {
      // 如果当前是第k个人,他只剩一次购票机会,购票之后就退出循环
      if (i === k && tickets[k] === 1) {
        // 购票时间加1
        result++
        // 购票数量减1
        tickets[k]--
        break
      }
      // 如果tickets[i]大于0,表示还可购票
      if (tickets[i]) {
        // 购票时间加1
        result++
        // 购票数量减1
        tickets[i]--
      }
    }
  }

  return result
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant