寻找数组中的中心点,使得左右两边的元素之和相等,并返回中心点元素,否则,返回-1(python)
思路:左边的元素之和 * 2 + 中心点元素 = 整个数组元素之和
1、python
class Solution(object):
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sum_nub = 0
d = {}
for i in nums:
sum_nub+=i
for i in range(len(nums)):
if not d:
d[i] = 0
else:
d[i] = d[i-1] + nums[i-1]
if d[i] * 2 + nums[i] == sum_nub:
return i
return -1
2、C++
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int size = nums.size();
int left_sum = 0;
int sum = 0;
for(int i=0; i<size; i++)
sum += nums[i];
for(int j=0; j<size; j++)
{
if(left_sum * 2 + nums[j] == sum)
return j;
left_sum += nums[j];
}
return -1;
}
};