1. 程式人生 > >leetcode 724. 尋找數組的中心索引(Find Pivot Index)

leetcode 724. 尋找數組的中心索引(Find Pivot Index)

解釋 cpp tro div 要求 整數 數組 solution tor

目錄

  • 題目描述:
  • 示例 1:
  • 示例 2:
  • 解法:

題目描述:

給定一個整數類型的數組 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 sum_val = 0;
        for(int val : nums){
            sum_val += val;
        }
        int sz = nums.size();
        int pre = 0;
        for(int i = 0; i < sz; i++){
            if(pre*2 + nums[i] == sum_val){
                return i;
            }else{
                pre += nums[i];
            }
        }
        return -1;
    }
};

leetcode 724. 尋找數組的中心索引(Find Pivot Index)