-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path19-724.ts
38 lines (31 loc) · 1006 Bytes
/
19-724.ts
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
// https://leetcode.com/problems/find-pivot-index/description/?envType=study-plan-v2&envId=leetcode-75
const pivotIndex = (nums: number[]): number => {
// O(N) SOLUTION, BUT UNACCEPTED; IT DOESN'T WORK PROPERLY WITH POSITIVE/NEGATIVE VALUES
// let i = 0,
// j = nums.length - 1,
// leftSum = 0,
// rightSum = 0;
// while (i < j) {
// const nextLeftSum = leftSum + nums[i];
// const nextRightSum = rightSum + nums[j];
// if (nextLeftSum > nextRightSum) {
// // if (Math.abs(nextLeftSum) > Math.abs(nextRightSum)) {
// rightSum = nextRightSum;
// j--;
// } else {
// leftSum = nextLeftSum;
// i++;
// }
// }
// return rightSum === leftSum ? i : -1;
// O(N) SOLUTION
let i = 1,
leftSum = 0,
rightSum = nums.reduce((acc, val) => acc + val, 0) - nums[0];
while (i < nums.length && leftSum !== rightSum) {
leftSum += nums[i - 1];
rightSum -= nums[i];
i++;
}
return leftSum === rightSum ? i - 1 : -1;
};