leetcode小白刷题之旅----724. Find Pivot Index
仅供自己学习
题目:
Given an array of integers nums, write a method that returns the "pivot" index of this array.
We define the pivot index as the index where the sum of all the numbers to the left of the index is equal to the sum of all the numbers to the right of the index.
If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.
Example 1:
Input: nums = [1,7,3,6,5,6]
Output: 3
Explanation:
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.
Example 2:
Input: nums = [1,2,3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.
思路:
下意识想的是从数据两侧靠近中心,但存在中心索引两侧数字数量不同的情况。因为存在多个中心索引的情况下选择最左侧的,于是考虑如果数组之和 - nums[ i ] = 2*左侧数之和 ,i 是从左侧开始增长,我们只需要考虑左侧的数的和的情况,不需要考虑中心索引右侧的情况,因为左侧数之和 *2 +nums[ i ] = total,确保了nums[ i ]一定满足 条件要求的中心,其一定在中部,否则不满足 等于数字总和。则可满足条件
代码:
1 class Solution { 2 public: 3 int pivotIndex(vector<int>& nums) { 4 int total=accumulate(nums.begin(),nums.end(),0); 5 int sum=0; 6 for(int i=0;i<nums.size();i++){ 7 if(total-nums[i]==2*sum) return i; 8 sum+=nums[i]; 9 } 10 return -1; 11 } 12 };

浙公网安备 33010602011771号