LeetCode75-724-Find-Pivot-Index

🧠 思路总结

找一个下标i,当 i左边的sum = i右边的sum时,返回i,否则返回-1。
解题关键: 数组总和 = 左边 + 当前元素 + 右边 (right = total - left - nums[i])

✅ 代码(Java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int pivotIndex(int[] nums) {
// rightSum = totalSum - leftSum - nums[i]
int total = 0;
for (int i = 0; i < nums.length; i++) {
total += nums[i];
}
int left = 0;
for (int i = 0; i < nums.length; i++) {
// left == right
if (left == total - left - nums[i]) {
return i;
}
left += nums[i];
}
return -1;
}
}

LeetCode75-724-Find-Pivot-Index
https://powersixxx.github.io/leetcode-blog/2026/02/06/LeetCode75-724-Find-Pivot-Index/
作者
Baowen Liu
发布于
2026年2月6日
许可协议