LeetCode 题解工作台
寻找数组的中心下标
给你一个整数数组 nums ,请计算数组的 中心下标 。 数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。 如果中心下标位于数组最左端,那么左侧数之和视为 0 ,因为在下标的左侧不存在元素。这一点对于中心下标位于数组最右端同样适用。 如果数组有多个中心下标,应该返回…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 前缀和
答案摘要
我们定义变量 表示数组 中下标 左侧元素之和,变量 表示数组 中下标 右侧元素之和。初始时 $left = 0$, $right = \sum_{i = 0}^{n - 1} nums[i]$。 遍历数组 ,对于当前遍历到的数字 ,我们更新 $right = right - x$,此时如果 ,说明当前下标 就是中间位置,直接返回即可。否则,我们更新 $left = left + x$…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路
题目描述
给你一个整数数组 nums ,请计算数组的 中心下标 。
数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。
如果中心下标位于数组最左端,那么左侧数之和视为 0 ,因为在下标的左侧不存在元素。这一点对于中心下标位于数组最右端同样适用。
如果数组有多个中心下标,应该返回 最靠近左边 的那一个。如果数组不存在中心下标,返回 -1 。
示例 1:
输入:nums = [1, 7, 3, 6, 5, 6] 输出:3 解释: 中心下标是 3 。 左侧数之和 sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 , 右侧数之和 sum = nums[4] + nums[5] = 5 + 6 = 11 ,二者相等。
示例 2:
输入:nums = [1, 2, 3] 输出:-1 解释: 数组中不存在满足此条件的中心下标。
示例 3:
输入:nums = [2, 1, -1] 输出:0 解释: 中心下标是 0 。 左侧数之和 sum = 0 ,(下标 0 左侧不存在元素), 右侧数之和 sum = nums[1] + nums[2] = 1 + -1 = 0 。
提示:
1 <= nums.length <= 104-1000 <= nums[i] <= 1000
注意:本题与主站 1991 题相同:https://leetcode.cn/problems/find-the-middle-index-in-array/
解题思路
方法一:前缀和
我们定义变量 表示数组 中下标 左侧元素之和,变量 表示数组 中下标 右侧元素之和。初始时 , 。
遍历数组 ,对于当前遍历到的数字 ,我们更新 ,此时如果 ,说明当前下标 就是中间位置,直接返回即可。否则,我们更新 ,继续遍历下一个数字。
遍历结束,如果没有找到中间位置,返回 。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
相似题目:
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
left, right = 0, sum(nums)
for i, x in enumerate(nums):
right -= x
if left == right:
return i
left += x
return -1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) for a single pass through the array or O(n) to build prefix sums. Space complexity is O(1) for single pass or O(n) for storing prefix sums. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect clarification on edge handling when pivot is at the start or end of the array.
- question_mark
Look for discussion on negative numbers affecting left-right sum comparison.
- question_mark
Observe if candidate optimizes space by avoiding a full prefix sum array.
常见陷阱
外企场景- error
Confusing left sum and right sum indices, especially at array boundaries.
- error
Not handling cases where no pivot exists and returning incorrect indices.
- error
Using extra space unnecessarily when a single pass can suffice.
进阶变体
外企场景- arrow_right_alt
Return all indices where left sum equals right sum instead of only the leftmost.
- arrow_right_alt
Find pivot index for a circular array where sums wrap around the end.
- arrow_right_alt
Determine pivot index with additional constraints, e.g., only even elements counted.