新增724. 寻找数组的中心索引 JavaScript版本

This commit is contained in:
jerryfishcode 2021-09-27 20:37:23 +08:00 committed by GitHub
parent 224dc5f561
commit 8edca00e48
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 11 additions and 0 deletions

View File

@ -129,6 +129,17 @@ func pivotIndex(nums []int) int {
## JavaScript
```js
var pivotIndex = function(nums) {
const sum = nums.reduce((a,b) => a + b);//求和
// 中心索引左半和 中心索引右半和
let leftSum = 0, rightSum = 0;
for(let i = 0; i < nums.length; i++){
leftSum += nums[i];
rightSum = sum - leftSum + nums[i];// leftSum 里面已经有 nums[i],多减了一次,所以加上
if(leftSum === rightSum) return i;
}
return -1;
};
```
-----------------------