724. Find Pivot Index

724. Find Pivot Index

Given an array of integers nums, calculate the pivot index of this array.

The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index’s right.

If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.

Return the leftmost pivot index. If no such index exists, return -1.

Example 1:

Input: nums = [1,7,3,6,5,6]
Output: 3
Explanation:
The pivot index is 3.
Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
Right sum = nums[4] + nums[5] = 5 + 6 = 11

Example 2:

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

Example 3:

Input: nums = [2,1,-1]
Output: 0
Explanation:
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums[1] + nums[2] = 1 + -1 = 0

Constraints:

  • 1 <= nums.length <= 104
  • -1000 <= nums[i] <= 1000

思路

最简单粗暴的思路:
首先创建一个从左到右的和数组 sums_l,数组的第 i 位存放 nums[0]nums[i-1] 的累加;
然后类似地创建一个从右到左的和数组 sums_r
最后将 i0nums.size() 过一遍,如果 sums_l[i] == sums_r[i],就返回 i

优化上述思路的空间:
不创建从右到左的和数组,保留整个数组的 sum
遍历 sums_l 的时候,每次检测 sums_l[i] * 2 + nums[i] == sum,满足就返回 i

再一次优化上面思路的空间:
写完上面版本的代码后,发现 sums_l 也不需要保存,第一次遍历实际只需要保存整个 nums 的和。
然后在第二次遍历时,计算 sum_2 = nums[0]nums[i-1] 的累加。如果 sum_2 * 2 + nums[i] == sum,就返回 i

class Solution {
public:
    int pivotIndex(vector<int>& nums) {
        int sum = 0;
        int size = nums.size();
        for (int i = 0; i < size; ++i) {
            sum += nums[i];
        }

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

};

Runtime: 20 ms, faster than 91.64% of C++ online submissions for Find Pivot Index.
Memory Usage: 30.9 MB, less than 81.95% of C++ online submissions for Find Pivot Index.

Leave a Comment