0724. 寻找数组的中心下标 #39
Replies: 14 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.
-
|
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.
-
为什么不直接用sum()求和?只需要用一个for loop, 虽然复杂度没变但是会快很多。
|
Beta Was this translation helpful? Give feedback.
-
您好,感谢您的提问,我看看了此题,直接使用sum求和,看起来更直观,但实际运行效率差非常多,因为我两边的数都要进行计算和维护,但是实质是右边的数可以通过左边何总数来计算出来,右边没必要再计算和;另外,如果在for里面使用sum函数的话,又增加了复杂度,因为sum的复杂度是O(n),总的复杂度就是O(n的平方)。
祝好
李驰强
李驰强
***@***.***
|
Beta Was this translation helpful? Give feedback.
-
因为数组无序,所以大方向上确实想不出什么好的方法。
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
0724. 寻找数组的中心下标 | 算法通关手册
https://algo.itcharge.cn/Solutions/0700-0799/find-pivot-index/
Beta Was this translation helpful? Give feedback.
All reactions