682.田径比赛(javascript)682.BaseballGame
原创你现在是一场采用特殊赛制棒球比赛的记录员。这场比赛由若干回合组成,过去几回合的得分可能会影响以后几回合的得分。
比赛开始时,记录是空白的。你会得到一个记录操作的字符串列表 ops,其中 ops[i] 是你需要记录的第 i 项操作,ops 遵循下述规则:
整数 x - 表示本回合新获得分数 x
“+” - 表示本回合新获得的得分是前两次得分的总和。题目数据保证记录此操作时前面总是存在两个有效的分数。
“D” - 表示本回合新获得的得分是前一次得分的两倍。题目数据保证记录此操作时前面总是存在一个有效的分数。
“C” - 表示前一次得分无效,将其从记录中移除。题目数据保证记录此操作时前面总是存在一个有效的分数。
请你返回记录中所有得分的总和。
You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings operations, where operations[i] is the ith operation you must apply to the record and is one of the following:
An integer x.
Record a new score of x.
‘+’.
Record a new score that is the sum of the previous two scores.
‘D’.
Record a new score that is the double of the previous score.
‘C’.
Invalidate the previous score, removing it from the record.
Return the sum of all the scores on the record after applying all the operations.
The test cases are generated such that the answer and all intermediate calculations fit in a 32-bit integer and that all operations are valid.
示例 1:
输入:ops = ["5","2","C","D","+"]
输出:30
解释:
"5" - 记录加 5 ,记录现在是 [5]
"2" - 记录加 2 ,记录现在是 [5, 2]
"C" - 使前一次得分的记录无效并将其移除,记录现在是 [5].
"D" - 记录加 2 * 5 = 10 ,记录现在是 [5, 10].
"+" - 记录加 5 + 10 = 15 ,记录现在是 [5, 10, 15].
所有得分的总和 5 + 10 + 15 = 30
示例 2:
输入:ops = ["5","-2","4","C","D","9","+","+"]
输出:27
解释:
"5" - 记录加 5 ,记录现在是 [5]
"-2" - 记录加 -2 ,记录现在是 [5, -2]
"4" - 记录加 4 ,记录现在是 [5, -2, 4]
"C" - 使前一次得分的记录无效并将其移除,记录现在是 [5, -2]
"D" - 记录加 2 * -2 = -4 ,记录现在是 [5, -2, -4]
"9" - 记录加 9 ,记录现在是 [5, -2, -4, 9]
"+" - 记录加 -4 + 9 = 5 ,记录现在是 [5, -2, -4, 9, 5]
"+" - 记录加 9 + 5 = 14 ,记录现在是 [5, -2, -4, 9, 5, 14]
所有得分的总和 5 + -2 + -4 + 9 + 5 + 14 = 27
示例 3:
输入:ops = ["1"]
输出:1
提示:
- 1 <= ops.length <= 1000
- ops[i] 为 “C”、“D”、“+”,或者一个表示整数的字符串。整数范围是 [-3 104, 3 104]
- 对于 “+” 操作,题目数据保证记录此操作时前面总是存在两个有效的分数
- 对于 “C” 和 “D” 操作,题目数据保证记录此操作时前面总是存在一个有效的分数
使用变长数组对栈进行模拟。
如果操作是 +,那么访问数组的后两个得分,将两个得分之和加到总得分,并且将两个得分之和入栈。
如果操作是 D,那么访问数组的最后一个得分,将得分乘以 2 加到总得分,并且将得分乘以 2 入栈。
如果操作是 C,那么访问数组的最后一个得分,将总得分减去该得分,并且将该得分出栈。
如果操作是整数,那么将该整数加到总得分,并且将该整数入栈。
/**
* @param {string[]} operations
* @return {number}
*/
var calPoints = function (operations) {
let sum = 0
let newList = []
for (let i = 0; i < operations.length; i++) {
let n = newList.length
if (operations[i] == +) {
sum += newList[n - 1] + newList[n - 2]
newList.push(newList[n - 1] + newList[n - 2])
} else if (operations[i] == D) {
sum += newList[n - 1] * 2
newList.push(newList[n - 1] * 2)
} else if (operations[i] == C) {
sum -= newList[n - 1]
newList.pop()
} else {
sum += parseInt(operations[i])
newList.push(parseInt(operations[i]))
}
}
return sum
};
leetcode : https://leetcode.cn/problems/baseball-game/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除