Runtime: 1 ms, faster than 100.00% of Java online submissions for Find Pivot Index. Memory Usage: 42.2 MB, less than 99.85% of Java online submissions for Find Pivot Index.
class Solution {
public int pivotIndex(int[] nums) {
int[] leftRight = new int[nums.length];
int[] rightLeft = new int[nums.length];
for(int i=nums.length-1; i>-1; i--) {
if(i==nums.length-1) {
rightLeft[i] = nums[i];
continue;
}
rightLeft[i] = nums[i] + rightLeft[i+1];
}
for(int i=0; i<nums.length; i++) {
if(i==0) {
leftRight[i] = nums[i];
continue;
}
leftRight[i] = nums[i] + leftRight[i-1];
}
for(int i=0; i<nums.length; i++) {
int right = 0;
int left = 0;
if(i>0) {
left = leftRight[i-1];
}
if(i<nums.length-1) {
right = rightLeft[i+1];
}
if(left == right) {
return i;
}
}
return -1;
}
}