LeetCode 724 尋找數組的中心索引 HERODING的LeetCode之路

給定一個整數類型的數組 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]的整數。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/find-pivot-index
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

解題思路:
首先定義總數和、最左元素和,接着計算出總數的和,最後再次遍歷數組,從左往右,判斷左右兩邊是否相等,不相等左邊繼續累加,判斷的依據是(sumLeft * 2 + nums[i] == sum),代碼如下:

class Solution {
   
   
public:
    int pivotIndex(vector<int>& nums) {
   
   
        // 定義總數和、最左元素和
        int sum = 0;
        int sumLeft = 0;
        // 求解總數和
        for(int i = 0; i < nums.size(); i ++) {
   
   
            sum += nums[i];
        }
        // 判斷左右兩邊是否相等
        for(int i = 0; i < nums.size(); i ++) {
   
   
            if(sumLeft * 2 + nums[i] == sum) {
   
   
                return i;
            }
            sumLeft += nums[i];
        }
        return -1;
    }
};


/*作者:heroding
鏈接:https://leetcode-cn.com/problems/find-pivot-index/solution/czui-rong-yi-li-jie-de-si-lu-by-heroding-twx5/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。*/

試了一下官方題解中使用的accumulate函數計算vector數組的總和,效率又進一步提高了!代碼如下:

class Solution {
   
   
public:
    int pivotIndex(vector<int> &nums) {
   
   
        int total = accumulate(nums.begin(), nums.end(), 0);
        int sum = 0;
        for (int i = 0; i < nums.size(); ++i) {
   
   
            if (2 * sum + nums[i] == total) {
   
   
                return i;
            }
            sum += nums[i];
        }
        return -1;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章