题目
代码
class Solution:
def findMiddleIndex(self, nums: List[int]) -> int:
all=sum(nums)
left=0
for i in range(len(nums)):
if left==(all-nums[i]-left):
return i
left+=nums[i]
return -1
【Java版本】
class Solution {
public int findMiddleIndex(int[] nums) {
int total = Arrays.stream(nums).sum();
int sum = 0;
for (int i = 0; i < nums.length; ++i) {
if (2 * sum + nums[i] == total) {
return i;
}
sum += nums[i];
}
return -1;
}
}