LeetCode 题解工作台
保龄球游戏的获胜者
给你两个下标从 0 开始的整数数组 player1 和 player2 ,分别表示玩家 1 和玩家 2 击中的瓶数。 保龄球比赛由 n 轮组成,每轮的瓶数恰好为 10 。 假设玩家在第 i 轮中击中 x i 个瓶子。玩家第 i 轮的价值为: 如果玩家在该轮的前两轮的任何一轮中击中了 10 个瓶子,则…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·模拟
答案摘要
我们可以用一个函数 计算出两个玩家的得分,分别记为 和 ,然后根据 和 的大小关系返回答案即可。 时间复杂度 ,其中 是数组的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·模拟 题型思路
题目描述
给你两个下标从 0 开始的整数数组 player1 和 player2 ,分别表示玩家 1 和玩家 2 击中的瓶数。
保龄球比赛由 n 轮组成,每轮的瓶数恰好为 10 。
假设玩家在第 i 轮中击中 xi 个瓶子。玩家第 i 轮的价值为:
- 如果玩家在该轮的前两轮的任何一轮中击中了
10个瓶子,则为2xi。 - 否则,为
xi。
玩家的得分是其 n 轮价值的总和。
返回
- 如果玩家 1 的得分高于玩家 2 的得分,则为
1; - 如果玩家 2 的得分高于玩家 1 的得分,则为
2; - 如果平局,则为
0。
示例 1:
输入:player1 = [5,10,3,2], player2 = [6,5,7,3]
输出:1
解释:
玩家 1 的分数为 5 + 10 + 2*3 + 2*2 = 25。
玩家 2 的分数为 6 + 5 + 7 + 3 = 21。
示例 2:
输入:player1 = [3,5,7,6], player2 = [8,10,10,2]
输出:2
解释:
玩家 1 的分数为 3 + 5 + 7 + 6 = 21。
玩家 2 的分数为 8 + 10 + 2*10 + 2*2 = 42。
示例 3:
输入:player1 = [2,3], player2 = [4,1]
输出:0
解释:
玩家 1 的分数为 2 + 3 = 5。
玩家 2 的分数为 4 + 1 = 5。
示例 4:
输入:player1 = [1,1,1,10,10,10,10], player2 = [10,10,10,10,1,1,1]
输出:2
解释:
玩家 1 的分数为 1 + 1 + 1 + 10 + 2*10 + 2*10 + 2*10 = 73。
玩家 2 的分数为 is 10 + 2*10 + 2*10 + 2*10 + 2*1 + 2*1 + 1 = 75。
提示:
n == player1.length == player2.length1 <= n <= 10000 <= player1[i], player2[i] <= 10
解题思路
方法一:模拟
我们可以用一个函数 计算出两个玩家的得分,分别记为 和 ,然后根据 和 的大小关系返回答案即可。
时间复杂度 ,其中 是数组的长度。空间复杂度 。
class Solution:
def isWinner(self, player1: List[int], player2: List[int]) -> int:
def f(arr: List[int]) -> int:
s = 0
for i, x in enumerate(arr):
k = 2 if (i and arr[i - 1] == 10) or (i > 1 and arr[i - 2] == 10) else 1
s += k * x
return s
a, b = f(player1), f(player2)
return 1 if a > b else (2 if b > a else 0)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for understanding of array manipulation and the simulation process.
- question_mark
Ensure that the candidate considers how to apply bonuses correctly in the later rounds.
- question_mark
Check whether the candidate can optimize the solution by calculating the scores in a single pass.
常见陷阱
外企场景- error
Not properly handling the bonus multiplier for subsequent rounds.
- error
Misinterpreting the problem by assuming that the scores in each round are constant or independent of prior rounds.
- error
Not considering edge cases like a tie or a very small number of rounds.
进阶变体
外企场景- arrow_right_alt
What if the bowling game has a larger number of rounds?
- arrow_right_alt
What if the scores for the players are zero for multiple turns?
- arrow_right_alt
How would the problem change if the bonus for hitting pins was different?