寻找数组的中心索引-Go实现

字数 10阅读 26
package main
import "fmt"

func pivotIndex(nums []int , n int)(isPivotIndex bool, idx int) {
    // in the first loop compute the summary of all numbers
    var sum = 0
    for i := 0; i < n; i++ {
        sum += nums[i]
    }

    // in the second loop find the index of pivot
    var left_sum = 0
    for i := 0; i < n; i++ {
        var right_sum = sum - left_sum - nums[i]
        if left_sum == right_sum {
            return true, i
        }
        left_sum += nums[i]
    }
    return false, -1
}

func pivotIndexHelper(nums []int , n int) {
    isPivotIndex, idx := pivotIndex(nums, n)
    if isPivotIndex {
        fmt.Printf("yes, pivot index is %d \n", idx)
    } else {
        fmt.Printf("no \n")
    }
}

func main() {
    pivotIndexHelper([]int {1, 7, 3, 6, 5, 6}, 6)
    pivotIndexHelper([]int {1, 2, 3}, 3)
}

最后的执行结果如下:

yes, pivot index is 3
no

推荐阅读更多精彩内容