GuilinDev

Lc0724

05 August 2008

724. Find Pivot Index

数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。找到这个中心下标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
    public int pivotIndex(int[] nums) {
        int sum = 0, leftSum = 0;
        sum = Arrays.stream(nums).sum();
        for (int i = 0; i < nums.length; i++) {
            if (leftSum == sum - leftSum - nums[i]) {
                return i;
            }
            // nums[i] is included into leftSum and will be minused in next round
            leftSum += nums[i]; 
        }
        return -1;
    }
}