Golang Leetcode 724. Find Pivot Index.go

2019-04-29 18:17:34 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1419707

思路

trick:先计算总和,然后判断什么时候等于一半

code

代码语言:javascript复制
func pivotIndex(nums []int) int {
	sum := 0
	for i := 0; i < len(nums); i   {
		sum  = nums[i]
	}
	if sum == nums[0] {
		return 0
	}
	half := 0
	for i := 1; i < len(nums); i   {
		half  = nums[i-1]
		if sum-nums[i]-half == half {
			return i
		}
	}
	return -1
}

0 人点赞