LeetCode 题解工作台
找到数组的中间位置
给你一个下标从 0 开始的整数数组 nums ,请你找到 最左边 的中间位置 middleIndex (也就是所有可能中间位置下标最小的一个)。 中间位置 middleIndex 是满足 nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[mi…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 前缀和
答案摘要
我们定义两个变量 和 ,分别表示数组 中下标 左侧元素之和和右侧元素之和。初始时 $l = 0$,而 $r = \sum_{i = 0}^{n - 1} nums[i]$。 我们遍历数组 ,对于当前遍历到的数字 ,我们更新 $r = r - x$,此时如果 $l = r$,说明当前下标 就是中间位置,直接返回即可。否则,我们更新 $l = l + x$,继续遍历下一个数字。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums ,请你找到 最左边 的中间位置 middleIndex (也就是所有可能中间位置下标最小的一个)。
中间位置 middleIndex 是满足 nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1] 的数组下标。
如果 middleIndex == 0 ,左边部分的和定义为 0 。类似的,如果 middleIndex == nums.length - 1 ,右边部分的和定义为 0 。
请你返回满足上述条件 最左边 的 middleIndex ,如果不存在这样的中间位置,请你返回 -1 。
示例 1:
输入:nums = [2,3,-1,8,4] 输出:3 解释: 下标 3 之前的数字和为:2 + 3 + -1 = 4 下标 3 之后的数字和为:4 = 4
示例 2:
输入:nums = [1,-1,4] 输出:2 解释: 下标 2 之前的数字和为:1 + -1 = 0 下标 2 之后的数字和为:0
示例 3:
输入:nums = [2,5] 输出:-1 解释: 不存在符合要求的 middleIndex 。
示例 4:
输入:nums = [1] 输出:0 解释: 下标 0 之前的数字和为:0 下标 0 之后的数字和为:0
提示:
1 <= nums.length <= 100-1000 <= nums[i] <= 1000
注意:本题与主站 724 题相同:https://leetcode.cn/problems/find-pivot-index/
解题思路
方法一:前缀和
我们定义两个变量 和 ,分别表示数组 中下标 左侧元素之和和右侧元素之和。初始时 ,而 。
我们遍历数组 ,对于当前遍历到的数字 ,我们更新 ,此时如果 ,说明当前下标 就是中间位置,直接返回即可。否则,我们更新 ,继续遍历下一个数字。
遍历结束,如果没有找到中间位置,返回 。
时间复杂度 ,其中 为数组 的长度。空间复杂度 。
相似题目:
class Solution:
def findMiddleIndex(self, nums: List[int]) -> int:
l, r = 0, sum(nums)
for i, x in enumerate(nums):
r -= x
if l == r:
return i
l += x
return -1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) due to a single pass through the array, and space complexity is O(1) since only cumulative sums are stored, making it efficient for the given constraints. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for a solution using a single left-to-right traversal with running sums.
- question_mark
Be careful with the first and last index where one side sum is zero.
- question_mark
Discuss how prefix sum logic reduces repeated summation calculations.
常见陷阱
外企场景- error
Calculating left and right sums separately at each index, leading to O(n^2) time.
- error
Ignoring the requirement to return the leftmost middle index first.
- error
Off-by-one errors when handling the first or last index sums.
进阶变体
外企场景- arrow_right_alt
Find all middle indices instead of only the leftmost one.
- arrow_right_alt
Consider arrays with floating-point numbers requiring precision checks.
- arrow_right_alt
Modify the problem to find middle index where left sum is greater than right sum by a fixed difference.