题目:
题解:
先求和,再遍历,一遇到解就可以返回了
代码:
class Solution {
public int pivotIndex(int[] nums)
{
int sum=0;
int prex=0;
for(int i = 0; i < nums.length; i++)
{
sum+=nums[i];
}
for(int i = 0; i < nums.length; i++)
{
if(prex==(sum-nums[i])/2&&(sum-nums[i])%2==0)
{
return i;
}
prex+=nums[i];
}
return -1;
}
}
官方的
class Solution {
public int pivotIndex(int[] nums) {
int total = Arrays.stream(nums).sum();
int sum = 0;
for (int i = 0; i < nums.length; ++i) {
if (2 * sum + nums[i] == total) {
return i;
}
sum += nums[i];
}
return -1;
}
}
还有双指针
class Solution {
public int pivotIndex(int[] nums) {
if(nums == null || nums.length == 0)
return -1;
int m = nums.length;
int i = 0;
int left = 0;
int right = 0;
for(int j=i+1;j<m;j++){
right+=nums[j];
}
for(i=1; i < m && left!=right; i++){
left += nums[i-1];
right-=nums[i];
}
return left==right?i-1:-1;
}
}
其他:
数组求和函数
int total = Arrays.stream(nums).sum();