寻找数组的中心下标基于Go

给定一个整数数组nums,编写一个能返回数组中心下标的方法。
中心下标:是数组的一个下标,其左侧所有元素相加的和等于右侧元素相加的和。
如果数组不存在,则返回-1.如果数组存在多个中心下标,返回最靠近左侧的那个。
注意:中心下标可能会出现在数组的两端。

package main

import "fmt"

func pivotIndex(nums []int)int{
	sum := 0//中心下标右侧和
	total := 0//中心下标左侧和
	for _, v := range nums{
		sum += v
	}

	// nums[i]为total和sum重合的部分
	for i:=0;i<len(nums);i++{
		total += nums[i]
		if total==sum{
			return i
		}
		// 不相等则sum减去nums[i],同时for循环的i++
		sum -= nums[i]
	}
	return -1
}

func main(){
	nums := []int{1,7,3,6,5,6}
	fmt.Println(pivotIndex(nums))
}
posted @ 2021-04-07 15:23  pangqianjin  阅读(247)  评论(0编辑  收藏  举报