2024-02-29|閱讀時間 ‧ 約 0 分鐘

問題化簡_尋找平衡軸心點_Leetcode 精選75題解析


題目敘述

題目會給我們一個整數陣列nums,要求我們計算平衡軸心點在哪?

平衡軸心的意思就是軸心點索引左側的元素總合 = 軸心點索引右側的元素總合

例如

整數陣列nums=[1,2,2,7,2,3]

7左側的元素總合為 1 + 2 + 2 = 5

7右側的元素總合為 2 + 3 = 5

所以7是平衡位置,其索引位置為3

所以平衡軸心索引位置 = 3

答案為3

題目的原文敘述


測試範例

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

陣列nums的長度介於1 ~ 10^4 之間。

  • -1000 <= nums[i] <= 1000

每個陣列元素都界於 -1000 ~ 1000之間。


演算法

分享至
成為作者繼續創作的動力吧!
Leetcode 國際版精選75題 上機考面試題 詳解 裡面包含: 1. 內涵題意解析 2. 演算法建造 3. python解題程式碼 4. 複雜度分析 5. 關鍵知識點提示
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

發表回應

成為會員 後即可發表留言