724. Find Pivot Index

144 阅读1分钟

724. Find Pivot Index

解题思路

1.pivot 的位置 sumLeft + pivot + sumRight = sum

2.那么如果 sumLeft === sumRight, sum = sumLeft * 2 + pivot

3.所以这个问题转化为 找一个值 加上 2倍左边sumLeft 的和等于数组中所有值的和

4.找到了直接返回这个值的inde即可

代码

/**
 * @param {number[]} nums
 * @return {number}
 */
var pivotIndex = function(nums) {
  if(nums.length === 1) return 0
  let sumLeft = 0
  let sum = nums.reduce((a,b) => a + b)

  for(let i = 0; i < nums.length;i++) {
      if(sumLeft * 2 + nums[i] === sum) {
          return i
      }
      sumLeft += nums[i]
  }
  return -1
};