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

淺談二分搜尋法

淺談二分搜尋法

Day 5 - For Loop

Day 5 - For Loop

結構命名

結構命名


Comments