LeetCode 724 Finding the center index of the array, the LeetCode path of HERODING

Given an array nums of integer type, write a method that returns the "center index" of the array.

We define the center index of the array like this: the sum of all the elements on the left of the center index of the array is equal to the sum of all the elements on the right.

If the array does not have a central index, then we should return -1. If the array has multiple center indexes, then we should return the one closest to the left.

Example 1:

Input:
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation:
The sum (1 + 7 + 3 = 11) of the left side of index 3 (nums[3] = 6), and the right The sum of the side numbers (5 + 6 = 11) is equal.
At the same time, 3 is also the first center index that meets the requirements.

Example 2:

Input:
nums = [1, 2, 3]
Output: -1
Explanation:
There is no center index that meets this condition in the array.

Description:

nums 的长度范围为 [0, 10000]。
任何一个 nums[i] 将会是一个范围在 [-1000, 1000]的整数。

Source: LeetCode
Link: https://leetcode-cn.com/problems/find-pivot-index The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Problem-solving idea:
first define the sum of the total and the leftmost element, then calculate the sum of the total, and finally traverse the array again, from left to right, to judge whether the left and right sides are equal, and the left side of the inequality continues to accumulate. The judgment is based on (sumLeft * 2 + nums[i] == sum), the code is as follows:

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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/

Tried the accumulate function used in the official solution to calculate the sum of the vector array, and the efficiency has been further improved! code show as below:

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;
    }
};

Guess you like

Origin blog.csdn.net/HERODING23/article/details/113285188