LeetCode 724. 寻找数组的中心下标
题目描述
思路分析
解法一:前缀和(推荐)
核心思路:
- 先求数组总和。
- 遍历数组维护左侧和,判断是否满足左侧和 == 总和 - 左侧和 - 当前值。
- 第一个满足条件的位置即为中心下标。
复杂度分析:
- 时间复杂度:O(n),其中 n 表示数组长度。
- 空间复杂度:O(1)。
class Solution {
public int pivotIndex(int[] nums) {
int total = 0;
for (int num : nums) {
total += num;
}
int left = 0;
for (int i = 0; i < nums.length; i++) {
if (left == total - left - nums[i]) {
return i;
}
left += nums[i];
}
return -1;
}
}
func pivotIndex(nums []int) int {
total := 0
for _, num := range nums {
total += num
}
left := 0
for i, num := range nums {
if left == total-left-num {
return i
}
left += num
}
return -1
}
相似题目
| 题目 | 难度 | 考察点 |
|---|---|---|
| 303. 区域和检索 - 数组不可变 | 简单 | 前缀和 |
| 560. 和为 K 的子数组 | 中等 | 前缀和 |
| 238. 除自身以外数组的乘积 | 中等 | 前后缀 |
| 1991. 找到数组的中间位置 | 简单 | 前缀和 |
| 724. 寻找数组的中心下标 | 简单 | 前缀和 |
本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0
许可协议,转载请注明出处!