问题描述:
Given an array of integers nums, calculate the pivot index of this array.
The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index’s right.
If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.
Return the leftmost pivot index. If no such index exists, return -1.
pivot index: 它左侧的子数组的和=它右侧的子数组的和,这个位置(index)被定义为pivot index
对于左侧/右侧边界,左侧/右侧子数组不存在,我们认为和为0
若没有,则返回-1
思路:
一边循环数组求和(sum)
然后逐个元素遍历,若其左侧之和其右侧之和,即sum_leftsum-它自己-sum_left, 我们返回该脚标
代码如下:
class Solution {
public int pivotIndex(int[] nums) {
int sum=0;
int left_sum=0;
for(int i=0; i<nums.length; i++){
sum+=nums[i];
}
for(int i=0; i<nums.length;i++){
if(left_sum==sum-left_sum-nums[i]){
return i;
}
left_sum+=nums[i];
}
return -1;
}
}
时间复杂度: O(n)