DAY41:Equal Sides Of An Array


Posted by birdbirdmurmur on 2023-08-23

題目連結:

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]儲存左邊的總和

左邊加總、右邊減去直到中間為止


#javascript #Codewars







Related Posts

W12_作業三簡答題記錄_之五

W12_作業三簡答題記錄_之五

Node.js & RESTful API - Wiki Project

Node.js & RESTful API - Wiki Project

D22_第三週解題

D22_第三週解題


Comments