0724. 寻找数组的中心下标 #39
Replies: 11 comments
-
if curr_sum * 2 + nums[i] == sum: 这块没太看明白 |
Beta Was this translation helpful? Give feedback.
-
这里 sum 是数组中所有元素和,curr_sum 是当前数组左侧元素和。 |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
其实没必要全部求和 class Solution:
def pivotIndex(self, nums: List[int]) -> int:
ListLen = len(nums)
Z_N = 0
Z_S = 0
MidList = []
SumNums = sum(nums)
for i in range (ListLen):
if(Z_S + Z_S == SumNums-nums[i]):
MidList.append(Z_N)
Z_S += nums[i]
Z_N += 1
if (len(MidList)==0):
return -1
else:
return MidList[0] |
Beta Was this translation helpful? Give feedback.
-
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
n=len(nums)
count=0
for i in range(n):
count+=nums[i]
if count-nums[0]==0:
return 0
for i in range(1,n):
left=0
right=0
if i>0:
for j in range(0,i):
left+=nums[j]
for j in range(i+1,n):
right+=nums[j]
if left==right:
return i
return -1
|
Beta Was this translation helpful? Give feedback.
-
这个解法当数组长度为2,有一个数为0的时候解不了 |
Beta Was this translation helpful? Give feedback.
-
class Solution:
|
Beta Was this translation helpful? Give feedback.
-
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
length = len(nums)
sumLeft = list()
sumRight = list()
sum = 0
for i in range(length):
sum += nums[i]
sumLeft.append(sum)
sumLeft.insert(0,0)
sum = 0
for i in range(length - 1, -1, -1):
sum += nums[i]
sumRight.append(sum)
sumRight.insert(0,0)
for i in range(length):
if sumLeft[i] == sumRight[length - i - 1]:
return i
return -1 |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
class Solution(object):
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sum_left = 0
sum_right = sum(nums) - nums[0]
if sum_left == sum_right:
return 0
for i in range(1, len(nums)):
sum_left += nums[i-1]
sum_right -= nums[i]
if sum_right == sum_left:
return i
return -1 |
Beta Was this translation helpful? Give feedback.
-
0724. 寻找数组的中心下标 | 算法通关手册
https://algo.itcharge.cn/Solutions/0700-0799/find-pivot-index/
Beta Was this translation helpful? Give feedback.
All reactions