iT邦幫忙

2022 iThome 鐵人賽

DAY 26
0
自我挑戰組

JavaScript - 30天 - 自學挑戰系列 第 26

LeetCode Js-724. Find Pivot Index

  • 分享至 

  • xImage
  •  

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:

  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

上一篇
LeetCode Js-205. Isomorphic Strings
下一篇
LeetCode Js-409. Longest Palindrome
系列文
JavaScript - 30天 - 自學挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言