#724 Find Pivot Index
題目解說:
這題有點看不懂他題目在講啥,也看不懂範例。後來google翻譯後
We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index
我們將pivot索引定義為索引的總和
索引左邊的數字等於 索引右邊的數字之和。
如果不存在這樣的索引,我們應該返回-1。 如果有多個數據透視索引,則應返回最左側的數據透視索引
當中的index 可以當作x ,x左邊的和要等於 x右邊的和, 如果沒有找到等於就回傳 -1,有找到多個的話,就回傳最左邊的的index值,不是元素哦,
如a[] = {2, 3, 5, 6, 5, ,3, 2 }, 當index到a[3] 的
左a[0] + a[1] + a[2] = 10
右a[4]+ a[5] + a[6] = 10
左10 == 右10 回傳index 3 不是回傳6 ( a[3] = 6 )
題目解析:
首先得到總total,然後用迴圈去跑,由index 0 開始到 最後一個index,每次都會判斷左邊是否等於右邊?是的話回傳該index值,迴圈跑完(中間有找到左==右,就馬上return,結束迴圈),回傳-1。
判斷 左邊的和是否等於右邊的和,用總total - 左total - 目前index值 = 得到右total。
迴圈裡最後一行,就要把該index的元素加到左total
程式碼 ↓
class Solution {
public int pivotIndex(int[] nums) {
int total = 0;
for(int element : nums){
total += element;
}
int leftSum = 0;
for(int index = 0 ; index < nums.length ; index++){
if( (total - leftSum - nums[index]) == leftSum ){
return index;
}
leftSum += nums[index];
}
return -1;
}
}
Last updated
Was this helpful?