From e9c5f17af52cbeee408e349d7a7655b5d711bc80 Mon Sep 17 00:00:00 2001 From: posper Date: Thu, 29 Jul 2021 18:48:56 +0800 Subject: [PATCH] =?UTF-8?q?724.=E5=AF=BB=E6=89=BE=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E7=9A=84=E4=B8=AD=E5=BF=83=E4=B8=8B=E6=A0=87=20=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0724.寻找数组的中心索引.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/problems/0724.寻找数组的中心索引.md b/problems/0724.寻找数组的中心索引.md index bf989979..09966e05 100644 --- a/problems/0724.寻找数组的中心索引.md +++ b/problems/0724.寻找数组的中心索引.md @@ -67,6 +67,24 @@ public: ## Java ```java +class Solution { + public int pivotIndex(int[] nums) { + int sum = 0; + for (int i = 0; i < nums.length; i++) { + sum += nums[i]; // 总和 + } + int leftSum = 0; + int rightSum = 0; + for (int i = 0; i < nums.length; i++) { + leftSum += nums[i]; + rightSum = sum - leftSum + nums[i]; // leftSum 里面已经有 nums[i],多减了一次,所以加上 + if (leftSum == rightSum) { + return i; + } + } + return -1; // 不存在 + } +} ``` ## Python @@ -90,4 +108,3 @@ public: * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
-