0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
---|---|---|---|---|---|---|---|
-1 | 4 | 3 | 9 | 3 | -2 | 4 | 1 |
寻找数组的中心索引
方法:前缀和
- 计算数组总的和totalSum
- 如果sum_left = sum_right,那么满足sum_left + sum_right + nums[i] = totalSum, 则返回 i 索引值
- 那么式子可变为sum_left + sum_left + nums[i] = totalSum------>2*sum_left + nums[i] = totalSum
时间复杂度O(N)
class Solution {
public int pivotIndex(int[] nums) {
int totalSum = 0;
int sumLeft = 0;
for(int item : nums){
totalSum += item;
}
for(int i=0; i<nums.length; i++){
if(sumLeft * 2 + nums[i] == totalSum){
return i;
}
sumLeft += nums[i];
}
return -1;
}
}
**前缀和算法:**数组的前 i 项之和,某一区间和为前缀和的运算,
S[1] = a[1]
S[2] = a[1] + a[2]
S[3] = a[1] + a[2] + a[3]
S[4] = a[1] + a[2] + a[3] + a[4]
S[2-3] = a[2] + a[3] = S[3] - S[1]