-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindPivotIndex.java
More file actions
40 lines (34 loc) · 948 Bytes
/
Copy pathFindPivotIndex.java
File metadata and controls
40 lines (34 loc) · 948 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
37
38
39
40
class Solution {
public int pivotIndex(int[] nums) {
if(nums == null || nums.length <= 1) return -1;
int n = nums.length;
int[] ps = new int[n+1];
ps[n] = 0;
for(int i = n-1; i >= 0; i--) {
ps[i] = ps[i+1] + nums[i];
}
int sum = 0;
for(int i = 0; i < n; i++) {
if(sum == ps[i+1]) return i;
sum += nums[i];
}
return -1;
}
}
// much easier to write code
class Solution {
public int pivotIndex(int[] nums) {
if(nums == null || nums.length == 0) throw new IllegalArgumentException("x");
int sum = 0;
int n = nums.length;
for(int i = 0; i < n; i++) {
sum += nums[i];
}
int ls = 0;
for(int i = 0; i<n; i++) {
if(sum-ls-nums[i] == ls) return i;
ls += nums[i];
}
return -1;
}
}