LeetCode Js-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.
給予一個 nums 的整數陣列,計算樞紐的索引值。
樞紐的索引代表:左邊的索引總和等於右邊的索引總和。
如果左邊或右邊的陣列是0或沒有元素在左邊或右邊,則回傳最左邊的樞紐索引,如不存在索引則返回-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
Solution:
Code:
var pivotIndex = function(nums) {
let sum = 0, leftSum = 0
for (let i = 0; i < nums.length; i++) {
sum += nums[i]
}
for (let i = 0; i < nums.length; i++) {
sum -= nums[i]
if (leftSum === sum) return i
leftSum += nums[i]
}
return -1
}
FlowChart:
Example 1
Input: nums = [1,7,3,6,5,6]
sum = 0, leftSum = 0
sum = 1 + 7 + 3 + 6 + 5 + 6 => 28
step.1
i = 0
sum -= nums[i] = 28 - 1 => 27
leftSum === sum => 0 !== 27
leftSum += nums[i] => 0 + 1 = 1
step.2
i = 1
sum -= nums[i] = 27 - 7 => 20
leftSum === sum => 1 !== 20
leftSum += nums[i] => 1 + 7 = 8
step.3
i = 2
sum -= nums[i] = 20 - 3 => 17
leftSum === sum => 1 !== 17
leftSum += nums[i] => 8 + 3 = 11
step.4
i = 3
sum -= nums[i] = 17 - 6 => 11
leftSum === sum => 11 === 11
return i //i = 3