724. 寻找数组的中心索引
题目描述
给你一个整数数组 nums,请编写一个能够返回数组 “中心索引” 的方法。
数组 中心索引 是数组的一个索引,其左侧所有元素相加的和等于右侧所有元素相加的和。
如果数组不存在中心索引,返回 -1 。如果数组有多个中心索引,应该返回最靠近左边的那一个。
注意:中心索引可能出现在数组的两端。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-pivot-index
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
输入样例:
nums = [1, 7, 3, 6, 5, 6]
nums = [1, 2, 3]
nums = [2, 1, -1]
输出样例:
3
-1
0
ac代码
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int size = nums.size();
int sum1 = 0,sum2 = 0;
for (int i = 1; i < size; i++) {
sum1 += nums[i];
}
int j = 1;
while (j - 1 != size) {
if (sum1 == sum2) {
return j - 1;
}
sum1 -= nums[j];
sum2 += nums[j - 1];
j++;
}
return -1;
}
};
心得:
第一次WA:while中判断最后一个有问题
第二次AC:解决了这个问题
官方方法:
官方思路:
求一个总和,总和包括前几个数字的和,后几个数字之和,中间那个数字之和
class Solution {
public:
int pivotIndex(vector<int> &nums) {
int total = accumulate(nums.begin(), nums.end(), 0);
int sum = 0;
for (int i = 0; i < nums.size(); ++i) {
if (2 * sum + nums[i] == total) {
return i;
}
sum += nums[i];
}
return -1;
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/find-pivot-index/solution/xun-zhao-shu-zu-de-zhong-xin-suo-yin-by-gzjle/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
该更新LeetCode了
呜呜呜,别骂了,别骂了