返回
LeetCode刷题记录-682. 棒球比赛,实时掌控棒球比赛
前端
2023-10-24 15:49:49
棒球比赛的规则
棒球比赛中,每场比赛由九个回合组成。每个回合中,客队率先击球,主队随后击球。每支球队轮流击球,直到三振出局或得到分数。当一支球队得到分数时,称为“得分”。
计分系统
- 单打:击球手击中球并安全上垒,记1分。
- 二垒打:击球手击中球并安全上垒,并推进到二垒,记2分。
- 三垒打:击球手击中球并安全上垒,并推进到三垒,记3分。
- 本垒打:击球手击中球并安全回到本垒,记4分。
- 三振出局:击球手连续三次挥空,被判三振出局,不得上垒。
实现算法
def calculate_score(game):
"""
Calculates the score of a baseball game.
Args:
game: A list of strings representing the events of the game.
Returns:
A list of integers representing the score of each team at the end of each inning.
"""
# Initialize the score of each team.
scores = [0, 0]
# Iterate over the events of the game.
for event in game:
# If the event is a number, it represents the number of runs scored by the current team.
if event.isdigit():
scores[0] += int(event)
# If the event is "X", it represents a strikeout.
elif event == "X":
scores[1] += 1
# If the event is "H", it represents a hit.
elif event == "H":
scores[0] += 1
# If the event is "E", it represents an error.
elif event == "E":
scores[1] += 1
# If the event is "D", it represents a double.
elif event == "D":
scores[0] += 2
# If the event is "T", it represents a triple.
elif event == "T":
scores[0] += 3
# If the event is "HR", it represents a home run.
elif event == "HR":
scores[0] += 4
# Return the score of each team at the end of each inning.
return scores
# Example
game = ["4", "H", "E", "X", "2", "D", "HR", "3", "X", "X"]
print(calculate_score(game))
# Output: [14, 3]
复杂度分析
- 时间复杂度:O(n),其中n是游戏中的事件数。
- 空间复杂度:O(1),因为我们只需要存储两个变量来跟踪每支球队的得分。
总结
棒球比赛的计分系统是一个经典的算法问题,它要求我们根据比赛的现场情况,准确地计算出每支球队的得分。这个问题可以通过模拟的方式来解决,即根据比赛的规则,一步一步地计算出每支球队的得分。
希望你能通过这篇文章,对棒球比赛的计分系统有一个更深入的了解。如果你对算法感兴趣,不妨尝试自己实现一下这个算法。