版权声明: https://blog.csdn.net/DL_wly/article/details/84946511
- 题目描述
给定一个整数类型的数组 nums
,请编写一个能够返回数组“中心索引”的方法。
我们是这样定义数组中心索引的:数组中心索引的左侧所有元素相加的和等于右侧所有元素相加的和。
如果数组不存在中心索引,那么我们应该返回 -1。如果数组有多个中心索引,那么我们应该返回最靠近左边的那一个。
- 解决思路
(1)计算nums中数组的总和sum;
(2)若当前元素的左边所有元素之和(sum_left)的两倍等于sum减当前元素的值,则返回当前元素对应下标;
(3)反之,返回-1;
- C++代码
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int i;
int sum_left = 0;
int sum = accumulate(nums.begin() , nums.end() , 0);
for(i = 0; i < nums.size(); i++){
if( (sum_left*2 + nums[i]) == sum ){
return i;
break;
}
else{
sum_left += nums[i];
}
}
return -1;
}
};