LeetCode- find the center of the array index

Subject description:

Given an integer type array nums, please write a method to return an array of "Center Index".

We center is defined as an array index: left of center of the array index is equal to the sum of all the elements on the right side and the sum of all elements.

If the central index array does not exist, then we should return -1. If the array has a plurality of central index, then we should return the one closest to the left.

Example 1:

Input: 
the nums = [1, 7, 3,. 6,. 5,. 6]
Output: 3
Explanation: 
Index 3 (nums [3] = 6 ) of the left and the number of (1 + 7 + 3 = 11), and the right and the number of sides (5 + 6 = 11) are equal.
Meanwhile, 3 is the first center in line with the requirements of the index.
Example 2:

Input: 
the nums = [. 1, 2,. 3]
Output: -1
explanation: 
the array center index satisfies this condition does not exist.

Ideas: The problem of reverse thinking can be used to iterate over the array, the total sum of all numbers in an array of statistics. Then through the array, each element holds the added value traversed leftsum, until meeting sum == leftsum * 2 + num [j], i.e., the index j is the index of the center of the array.

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

 

Published 120 original articles · won praise 17 · views 20000 +

Guess you like

Origin blog.csdn.net/tangya3158613488/article/details/104066186