Kotlin Leetcode - 1588. Sum of All Odd Length Subarrays
class Solution {
fun sumOddLengthSubarrays(arr: IntArray): Int {
}
}
解題思路
這一題考的是對陣列的處理
用 forEachIndexed
可以很簡單的處理
Kotlin 參考解答
class Solution {
fun sumOddLengthSubarrays(arr: IntArray): Int {
var sum = 0
var slider = 0
while (slider < arr.size) {
arr.forEachIndexed { index, _ ->
val endIndex = index + slider
if (endIndex < arr.size) {
val subArray = arr.slice(index..endIndex)
sum += subArray.sum()
}
}
slider += 2
}
return sum
}
}
回到 leetcode 列表