# LeetCode Solution, Easy, 724. Find Pivot Index

# [724. Find Pivot Index](https://leetcode.com/problems/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 <= 10**4`
- `-1000 <= nums[i] <= 1000`

**Note:** This question is the same as 1991: <https://leetcode.com/problems/find-the-middle-index-in-array/>

**Hint 1:**

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

### 題目翻譯

這題是要找出中間錨點的索引，中間錨點會拆分左右兩邊，其兩側的總和需要相等。如果沒有滿足條件的位置，就回傳 `-1`。如果有多個滿足條件的錨點，就回傳最左側的。

## 解法解析

此題與 [1991](https://blog.taiwolskit.com/leetcode-solution-easy-1991-find-the-middle-index-in-array) 相同。
利用左右兩側相同的原則 `sum = leftsum + rightsum + x`，就會等於 `sum = 2 * leftsum + x`。所以先找出總和，然後再比對。

### 解法範例

#### Go

```go
func pivotIndex(nums []int) int {
	var S int = 0
	for _, v := range nums {
		S += v
	}
	var leftsum int = 0
	for i, x := range nums {
		if leftsum == S-leftsum-x {
			return i
		}
		leftsum += x
	}
	return -1
}
```

#### JavaScript

```javascript
/**
 * @param {number[]} nums
 * @return {number}
 */
var pivotIndex = function (nums) {
    const S = nums.reduce((a, b) => a + b, 0);
    let leftsum = 0;
    for (let i = 0; i < nums.length; i++) {
        if (leftsum === S - leftsum - nums[i]) {
            return i;
        }
        leftsum += nums[i];
    }
    return -1;
};
```

#### Kotlin

```kotlin
class Solution {
    fun pivotIndex(nums: IntArray): Int {
        val sum = nums.sum()
        var leftSum = 0
        for ((i, num) in nums.withIndex()) {
            if (leftSum == (sum - leftSum - num)) {
                return i
            }
            leftSum += num
        }
        return -1
    }
}
```

#### PHP

```php
class Solution
{

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function pivotIndex($nums)
    {
        $sum = array_sum($nums);
        $leftSum = 0;
        foreach ($nums as $i => $num) {
            if ($leftSum == $sum - $leftSum - $num) {
                return $i;
            }
            $leftSum += $num;
        }
        return -1;
    }
}
```

#### Python

```python
class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        S = sum(nums)
        leftsum = 0
        for i, x in enumerate(nums):
            if leftsum == (S - leftsum - x):
                return i
            leftsum += x
        return -1
```

#### Rust

```rust
```

#### Swift

```swift
class Solution {
    func pivotIndex(_ nums: [Int]) -> Int {
        let sum = nums.reduce(0, +)
        var leftSum = 0
        for (i, num) in nums.enumerated() {
            if leftSum == sum - leftSum - num {
                return i
            }
            leftSum += num
        }
        return -1
    }
}
```

