-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPivotFinder.java
More file actions
36 lines (28 loc) · 826 Bytes
/
PivotFinder.java
File metadata and controls
36 lines (28 loc) · 826 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package org.sean.array;
/***
* 724. Find Pivot Index
*/
public class PivotFinder {
public int pivotIndex(int[] nums) {
if (nums == null || nums.length == 0) return -1;
if (nums.length == 1) return 0;
int length = nums.length;
// Arrays.stream(nums).sum();
int sum = 0;
for (int i = 0; i < length; i++) {
sum += nums[i];
}
// check the left boundary
if (sum - nums[0] == 0) return 0;
int currentSum = nums[0];
for (int i = 1; i < length; i++) {
if (currentSum == sum - nums[i] - currentSum) {
return i;
}
currentSum += nums[i];
}
// check the right boundary
if (sum - nums[length - 1] == 0) return length - 1;
return -1;
}
}