存在一种仅支持 4 种操作和 1 个变量 X 的编程语言:
++X 和 X++ 使变量 X 的值 加 1
--X 和 X-- 使变量 X 的值 减 1
最初,X 的值是 0
给你一个字符串数组 operations ,这是由操作组成的一个列表,返回执行所有操作后, X 的 最终值 。
示例 1:输入:operations = ["--X","X++","X++"] 输出:1
解释:操作按下述步骤执行:
最初,X = 0
--X:X 减 1 ,X = 0 - 1 = -1
X++:X 加 1 ,X = -1 + 1 = 0
X++:X 加 1 ,X = 0 + 1 = 1
示例 2:输入:operations = ["++X","++X","X++"] 输出:3
解释:操作按下述步骤执行:
最初,X = 0
++X:X 加 1 ,X = 0 + 1 = 1
++X:X 加 1 ,X = 1 + 1 = 2
X++:X 加 1 ,X = 2 + 1 = 3
示例 3:输入:operations = ["X++","++X","--X","X--"] 输出:0
解释:操作按下述步骤执行:
最初,X = 0
X++:X 加 1 ,X = 0 + 1 = 1
++X:X 加 1 ,X = 1 + 1 = 2
--X:X 减 1 ,X = 2 - 1 = 1
X--:X 减 1 ,X = 1 - 1 = 0
提示:1 <= operations.length <= 100
operations[i] 将会是 "++X"、"X++"、"--X" 或 "X--"
1、遍历;时间复杂度O(n),空间复杂度O(1)
func finalValueAfterOperations(operations []string) int {
res := 0
for i := 0; i < len(operations); i++ {
if operations[i][1] == '+' {
res++
} else {
res--
}
}
return res
}
2、遍历;时间复杂度O(n),空间复杂度O(1)
func finalValueAfterOperations(operations []string) int {
res := 0
for i := 0; i < len(operations); i++ {
if strings.Contains(operations[i], "+") {
res++
} else {
res--
}
}
return res
}
Easy题目,直接遍历判断即可
页面更新:2024-05-11
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号