mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
/0724.寻找数组的中心索引.md, 增加Goalng实现
This commit is contained in:
@ -9,6 +9,8 @@
|
|||||||
|
|
||||||
# 724.寻找数组的中心下标
|
# 724.寻找数组的中心下标
|
||||||
|
|
||||||
|
[力扣题目链接](https://leetcode-cn.com/problems/find-pivot-index/)
|
||||||
|
|
||||||
给你一个整数数组 nums ,请计算数组的 中心下标 。
|
给你一个整数数组 nums ,请计算数组的 中心下标 。
|
||||||
|
|
||||||
数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。
|
数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。
|
||||||
@ -87,9 +89,9 @@ class Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Python
|
## Python3
|
||||||
|
|
||||||
```python3
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
def pivotIndex(self, nums: List[int]) -> int:
|
def pivotIndex(self, nums: List[int]) -> int:
|
||||||
numSum = sum(nums) #数组总和
|
numSum = sum(nums) #数组总和
|
||||||
@ -104,6 +106,24 @@ class Solution:
|
|||||||
## Go
|
## Go
|
||||||
|
|
||||||
```go
|
```go
|
||||||
|
func pivotIndex(nums []int) int {
|
||||||
|
sum := 0
|
||||||
|
for _, v := range nums {
|
||||||
|
sum += v;
|
||||||
|
}
|
||||||
|
|
||||||
|
leftSum := 0 // 中心索引左半和
|
||||||
|
rightSum := 0 // 中心索引右半和
|
||||||
|
for i := 0; i < len(nums); i++ {
|
||||||
|
leftSum += nums[i]
|
||||||
|
rightSum = sum - leftSum + nums[i]
|
||||||
|
if leftSum == rightSum{
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## JavaScript
|
## JavaScript
|
||||||
|
Reference in New Issue
Block a user