724 Find Pivot Index
Given an array of integersnums
, write a method that returns the "pivot" index of this array.
We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.
Example 1:
Example 2:
Note:
The length ofnums
will be in the range[0, 10000]
.
Each elementnums[i]
will be an integer in the range[-1000, 1000]
.
这题用prefix sum,先把O(N)把所有数字的sum算出来,然后左边加右边减找出左右和相等的。这里要注意的是,中间其实跳过了一个数字,所以要先减右边,判断完,再加到左边。
Last updated