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
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
Solution:
1. 先設定 sum = 0, leftSum = 0。
2. 用 for 迴圈,將 nums 中的整數加總。
3. 用 for 迴圈,將 sum 逐一扣除 nums 中的整數。
4. 同時 if 條件,將 leftSum 與 sum做比對,符合則回傳 i (樞紐值)。
5. 如否,則將 leftSum 逐一加入 nums 中的整數。(左邊望大,右邊望小逐一比對)
6. 如 for 迴圈執行完沒有提前跳出,則回傳 -1。
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
Example 2
Input: nums = [1,2,3] sum = 0, leftSum = 0 sum = 1 + 2 + 3 => 6 step.1 i = 0 sum -= nums[i] = 6 - 1 => 5 leftSum === sum => 0 !== 5 leftSum += nums[i] => 0 + 1 = 1 step.2 i = 1 sum -= nums[i] = 5 - 2 => 3 leftSum === sum => 1 !== 3 leftSum += nums[i] => 1 + 2 = 3 step.2 i = 2 sum -= nums[i] = 3 - 3 => 0 leftSum === sum => 3 !== 0 leftSum += nums[i] => 3 + 3 = 6 return -1
Example 3
Input: nums = [2,1,-1] sum = 0, leftSum = 0 sum = 2 + 1 + -1 => 2 step.1 i = 0 sum -= nums[i] = 2 - 2 => 0 leftSum === sum => 0 === 0 return i //i = 0