当前位置:网站首页>Leetcode 724. Find the central subscript of the array (yes, once)

Leetcode 724. Find the central subscript of the array (yes, once)

2022-06-27 14:05:00 I'm not xiaohaiwa~~~~

 Insert picture description here
Give you an array of integers nums , Please calculate the of the array Center subscript .

Array Center subscript Is a subscript of the array , The sum of all elements on the left is equal to the sum of all elements on the right .

If the central subscript is at the leftmost end of the array , Then the sum of the numbers on the left is regarded as 0 , Because there is no element to the left of the subscript . This also applies to the fact that the central subscript is at the rightmost end of the array .

If the array has multiple central subscripts , Should return to Closest to the left The one of . If the array does not have a central subscript , return -1 .

Example 1:

 Input :nums = [1, 7, 3, 6, 5, 6]
 Output :3
 explain :
 The central subscript is  3 .
 The sum of the numbers on the left  sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 ,
 The sum of the numbers on the right  sum = nums[4] + nums[5] = 5 + 6 = 11 , Two equal .

Example 2:

 Input :nums = [1, 2, 3]
 Output :-1
 explain :
 There is no central subscript in the array that satisfies this condition .

Example 3:

 Input :nums = [2, 1, -1]
 Output :0
 explain :
 The central subscript is  0 .
 The sum of the numbers on the left  sum = 0 ,( Subscript  0  There is no element on the left ),
 The sum of the numbers on the right  sum = nums[1] + nums[2] = 1 + -1 = 0 .

Tips :

  • 1 <= nums.length <= 10^4
  • -1000 <= nums[i] <= 1000

Code:

class Solution {
    
public:
    int pivotIndex(vector<int>& nums) {
    
        int left=0;
        int right=0;
        for(int i=0;i<nums.size();i++)
        {
    
            if(i!=0)
                left=accumulate(nums.begin(),nums.begin()+i,0);
            right=accumulate(nums.begin()+i+1,nums.end(),0);

      // cout<<left<<" "<<right<<endl;
            if(left==right)
                return i;
        }
        return -1;
    }
};
原网站

版权声明
本文为[I'm not xiaohaiwa~~~~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206271351030492.html