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

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
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容