From 8edca00e487878a00b16a296b35ff9a14fb3cb2f Mon Sep 17 00:00:00 2001 From: jerryfishcode <91447694+jerryfishcode@users.noreply.github.com> Date: Mon, 27 Sep 2021 20:37:23 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E724.=20=E5=AF=BB=E6=89=BE?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E7=9A=84=E4=B8=AD=E5=BF=83=E7=B4=A2=E5=BC=95?= =?UTF-8?q?=20JavaScript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0724.寻找数组的中心索引.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/problems/0724.寻找数组的中心索引.md b/problems/0724.寻找数组的中心索引.md index 991ce647..d5fa48ee 100644 --- a/problems/0724.寻找数组的中心索引.md +++ b/problems/0724.寻找数组的中心索引.md @@ -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; +}; ``` -----------------------