Leetcode 1991. Find the Middle Index in Array

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Partition Array Into Three Parts With Equal Sum

2. Solution

解析:Version 1,先统计出数组的总和,遍历数组,分别统计index左右两部分,如果相等,返回index

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
class Solution:
def findMiddleIndex(self, nums: List[int]) -> int:
total = sum(nums)
left = 0
right = total
for index, num in enumerate(nums):
right -= num
if left == right:
return index
left += num
return -1

Reference

  1. https://leetcode.com/problems/find-the-middle-index-in-array/
如果有收获,可以请我喝杯咖啡!