題目連結:
https://www.codewars.com/kata/5679aa472b8f57fb8c000047
解法:
function findEvenIndex(arr) {
let sum = arr.reduce((a, b) => a + b, 0)
let left = 0
for (let i = 0; i < arr.length; i++) {
sum -= arr[i]
if (sum === left) {
return i
}
left += arr[i]
}
return -1
}
筆記:
先將arr的總和計算出來
arr.reduce((a, b) => a + b, 0)
先sum -= arr[i]
後判斷
是否 sum === left + arr[i]
時
如果!==
left += arr[i]
儲存左邊的總和
左邊加總、右邊減去直到中間為止