寻找数组的中心索引

01234567
-14393-241

寻找数组的中心索引

方法:前缀和

  1. 计算数组总的和totalSum
  2. 如果sum_left = sum_right,那么满足sum_left + sum_right + nums[i] = totalSum, 则返回 i 索引值
  3. 那么式子可变为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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值