力扣刷题日记12---剑指 Offer II 012. 左右两边子数组的和相等
给你一个整数数组 nums ,请计算数组的 中心下标 。
数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。
如果中心下标位于数组最左端,那么左侧数之和视为 0 ,因为在下标的左侧不存在元素。这一点对于中心下标位于数组最右端同样适用。
如果数组有多个中心下标,应该返回 最靠近左边 的那一个。如果数组不存在中心下标,返回 -1 。
示例 1:
输入:nums = [1,7,3,6,5,6]
输出:3
解释:
中心下标是 3 。
左侧数之和 sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 ,
右侧数之和 sum = nums[4] + nums[5] = 5 + 6 = 11 ,二者相等。
示例 2:
输入:nums = [1, 2, 3]
输出:-1
解释:
数组中不存在满足此条件的中心下标。
示例 3:
输入:nums = [2, 1, -1]
输出:0
解释:
中心下标是 0 。
左侧数之和 sum = 0 ,(下标 0 左侧不存在元素),
右侧数之和 sum = nums[1] + nums[2] = 1 + -1 = 0 。
提示:
1 <= nums.length <= 104
-1000 <= nums[i] <= 1000
还是可以使用前缀和解法,思路如下:题目要求找到某位置(下标为 k),使左侧元素之和(设为sumLeft)与右侧元素之和(设为sumRight)相等,即满足等式 sumLeft + nums[k] + sumRight = total;和 sumLeft = sumRight。根据这两个公式可得: 2 * sumLeft + nums[k] = total。那么,我们就可以在从头遍历该数组的同时判断这个公式是否成立,如果成立,k 即为要找的答案(此时满足最靠近左侧);反之,遍历完都没有满足该等式,说明不存在中心下标,返回 -1。
代码如下:
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int size = nums.size();
int total = 0, sumLeft = 0;
for(int i = 0; i < size; ++i)
total += nums[i];
// 上面的for循环可以用STL的库函数实现
//total = accumulate(nums.begin(), nums.end(), 0);
for(int i = 0; i < size; ++i){
if(2 * sumLeft + nums[i] == total)
return i;
sumLeft += nums[i];
}
return -1;
}
};
时间复杂度:O(n);空间复杂度:O(1)。
还有另外一种判断方法,即 左边的和 = 右边的和。基本原理一样,只是要注意是先加 nums[i] 还是后加 nums[i]。
代码如下:
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int size = nums.size();
int total = 0, sumLeft = 0;
for(int i = 0; i < size; ++i)
total += nums[i];
// 上面的for循环可以用STL的库函数实现
//total = accumulate(nums.begin(), nums.end(), 0);
//1、
// for(int i = 0; i < size; ++i){
// if(sumLeft + nums[i] == total - sumLeft)
// return i;
// sumLeft += nums[i];
// }
//2、
for(int i = 0; i < size; ++i){
sumLeft += nums[i];
if(sumLeft - nums[i] == total - sumLeft)
return i;
}
return -1;
}
};