寻找数组的中心索引(724)
/**
 * 中心索引:数组的中心索引,左侧所有元素之和等于右侧所有元素之和。如果存在多个中心索引,则返回靠左的那个。
 */
public class Demo {

    /**
     * 方法:前缀和,即判断当i时,(总和 - i左侧元素之和 - i == i左侧元素之和)即可
     */
    public int pivotIndex(int[] nums) {
        int sum = 0, leftSum = 0;
        for (int num : nums) {
            sum += num;
        }
        for (int i = 0; i < nums.length; i++) {
            if (leftSum == sum - nums[i] - leftSum) return i;
            leftSum += nums[i];
        }
        return -1;
    }

    @Test
    public void test() {
        System.out.println(pivotIndex(new int[]{1, 7, 3, 6, 5, 6}));
    }
}
文章作者: koral
文章链接: http://luokaiii.github.io/2020/10/22/LeetCode/第一章:数组和字符串/1.寻找数组的中心索引-724/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自