Try   HackMD

LeetCode 日記 #012: 724. Find Pivot Index|Prefix Sum|找中心索引

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

題解

  1. 創建一個從左到右的前綴和陣列,包含了從索引 0 到索引 i-1 的所有元素和。
  2. 創建一個從右到左的前綴和陣列,包含了從索引 i+1 到索引 length-1 的所有元素和。
索引 i nums[i] sumLeft[i] (左側和) sumRight[i] (右側和) 是否相等?
0 1 0 27
1 7 1 20
2 3 8 17
3 6 11 11 是 ✓
4 5 17 6
5 6 22 0
class Solution {
    public int pivotIndex(int[] nums) {
        int length = nums.length;
        int[] sumLeft = new int[length];
        int[] sumRight = new int[length];

        sumLeft[0] = 0;
        for (int i = 1; i < length; i++) {
            sumLeft[i] = sumLeft[i - 1] + nums[i - 1]; 
        }

        sumRight[length - 1] = 0;
        for (int i = length - 2; i >= 0; i--) {
            sumRight[i] = sumRight[i + 1] + nums[i + 1];
        }

        for (int i = 0; i < length; i++) {
            if (sumLeft[i] == sumRight[i]) {
                return i;
            }
        }
        return -1;
    }
}

另一種方式:空間複雜度為 O(1)

  1. 先求陣列總和。
  2. 維護一個 leftSum 變數作為左邊前綴和。
  3. 迭代當下用 total 扣除 leftSum 和當下元素來取得右邊前綴和。
  4. 判斷左右是否相等。
class Solution {
    public int pivotIndex(int[] nums) {
        int total = 0;
        for (int num : nums) {
            total += num;
        }

        int leftSum = 0;
        for (int i = 0; i < nums.length; i++) {
            int rightSum = total - leftSum - nums[i];
            if (leftSum == rightSum) {
                return i;
            }
            leftSum += nums[i];
        }
        return -1;
    }
}