LeetCode724. Find Pivot Index

Given an array of integers nums, 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:

1
2
3
4
5
6
Input: 
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation:
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.

Example 2:

1
2
3
4
5
Input: 
nums = [1, 2, 3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.

Note:

  • The length of nums will be in the range [0, 10000].
  • Each element nums[i] will be an integer in the range [-1000, 1000].

Hint:

  • We can precompute prefix sums P[i] = nums[0] + nums[1] + … + nums[i-1].
  • Then for each index, the left sum is P[i]
  • the right sum is P[P.length - 1] - P[i] - nums[i].

思路

  • dp
  • 将i的左侧总和记为sum[i]
  • i的右侧总和:sum[length] - sum[i] - nums[i]
  • 跟hint不一样,我的sum.size()=length+1,sum[0]=0.因为i=0时,左侧没有数

my code in c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int pivotIndex(vector<int>& nums) {
vector<int> sum;
sum.push_back(0);//nums[0]left的sum是0.不能push_back nums[0]!!!

for (int i=1;i<=nums.size();i++)
{
sum.push_back(sum[i - 1] + nums[i-1]);
}
for (int i = 0; i < nums.size(); i++)
{
if (sum[i] == sum[nums.size()] - sum[i] - nums[i])
return i;
}
return -1;
}
};

细节

​ 1. 我的思路是 sum[i]不包含 nums[i] 本身。所以vector第一个数不是nums[0],是0.

LC in py

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def pivotIndex(self, nums):
# Time: O(n)
# Space: O(1)
left, right = 0, sum(nums)
for index, num in enumerate(nums):
right -= num
if left == right:
return index
left += num
return -1
  • 设left=0,right=total
  • 从nums的头开始遍历,right-nums[i],
    • 如果left==right,返回当前的i
    • 否则 left+nums[i]
  • 没有left==right,返-1

总结

  1. 计算不含nums[i]的leftsum,如果leftsum== total - leftsum -nums[i],返回i
  2. 设leftsum=0,rightsum=total.从头开始遍历,rightsum-nums[i];如果left=right ,返i,否则left+=nums[i];没有返-1
Thanks for Support.