Kotlin Leetcode - 2011. Final Value of Variable After Performing Operations
class Solution {
fun finalValueAfterOperations(operations: Array<String>): Int {
}
}
解題思路
這一題考的是陣列元素的個數計算
我們將 X++
和 ++X
的個數計算出來後
減去剩餘元素的個數
就可以得到答案
Kotlin 參考解答
class Solution {
fun finalValueAfterOperations(A: Array<String>) =
(A.filter{ it == "X++" || it == "++X" }.size) - (A.size - A.filter{ it == "X++" || it == "++X" }.size)
}
如果希望更加簡潔,移項一下可以得到
class Solution {
fun finalValueAfterOperations(A: Array<String>) =
2 * A.filter{ it == "X++" || it == "++X" }.size - A.size
}
回到 leetcode 列表