Leetcode724.Find Pivot Index尋找陣列的中心索引
阿新 • • 發佈:2018-11-09
給定一個整數型別的陣列 nums,請編寫一個能夠返回陣列“中心索引”的方法。
我們是這樣定義陣列中心索引的:陣列中心索引的左側所有元素相加的和等於右側所有元素相加的和。
如果陣列不存在中心索引,那麼我們應該返回 -1。如果陣列有多箇中心索引,那麼我們應該返回最靠近左邊的那一個。
示例 1:
輸入: nums = [1, 7, 3, 6, 5, 6] 輸出: 3 解釋: 索引3 (nums[3] = 6) 的左側數之和(1 + 7 + 3 = 11),與右側數之和(5 + 6 = 11)相等。 同時, 3 也是第一個符合要求的中心索引。
示例 2:
輸入: nums = [1, 2, 3] 輸出: -1 解釋: 陣列中不存在滿足此條件的中心索引。
說明:
- nums 的長度範圍為 [0, 10000]。
- 任何一個 nums[i] 將會是一個範圍在 [-1000, 1000]的整數。
class Solution { public: int pivotIndex(vector<int>& nums) { int len = nums.size(); if(len <= 1) { return len == 0? -1 : 0; } vector<int> temp(len, 0); int sum = 0; for(int i = 0; i < len; i++) { sum += nums[i]; temp[i] = sum; } for(int i = 0; i < len; i++) { int left = 0; int right = 0; if(i == 0) { left = 0; right = temp[len - 1] - temp[i]; } else if(i == len -1) { left = temp[i - 1]; right = 0; } else { left = temp[i - 1]; right = temp[len - 1] - temp[i]; } if(left == right) return i; } return -1; } };