Open songyy5517 opened 6 months ago
Approach: Prefix Sum
left_sum = 0
: the sum of the current left part;total_sum = sum[0:len-1]
: the total sum of the whole array.left_sum == right_sum = total_sum - nums[i] - left_sum
, if so, return the current index;
(2)Update the sum of the left part left_sum += nums[i]
;Complexity Analysis
class Solution {
public int pivotIndex(int[] nums) {
// Intuition: Prefix sum.
// 1. Exception handling
if (nums == null || nums.length == 0)
return -1;
// 2. Define variables
int left_sum = 0;
int total_sum = 0;
for (int num : nums)
total_sum += num;
// 3. Loop through the array to find the pivot index
for (int i = 0; i < nums.length; i++){
if (left_sum == total_sum - nums[i] - left_sum)
return i;
left_sum += nums[i];
}
return -1;
}
}
2024/5/15
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.
Example 1:
Example 2:
Example 3:
Intuition This problem is to find an element in the array which can seperate the entire array into two parts and keep the sum of these two parts equal. A straightforward idea is that we can see the total sum of the raw array as three parts:
[left_sum, nums[i], right_sum]
. Therefore, we haveright_sum = total_sum - nums[i] - left_sum
. Loop through the array, and take each element as the pivot element, we need to determine whetherleft_sum == right_sum = total_sum - nums[i] - left_sum
. If yes, then return the current index; return -1 otherwise.