Skip to content

Commit 83fb8fd

Browse files
authored
Create 1991-find-the-middle-index-in-array.js
1 parent f6f52d0 commit 83fb8fd

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
const findMiddleIndex = function(nums) {
6+
const n = nums.length, leftSum = Array(n + 1).fill(0)
7+
const sum = nums.reduce((ac, e) => ac + e, 0)
8+
for(let i = 0; i < n; i++) {
9+
leftSum[i+1] = leftSum[i] + nums[i]
10+
}
11+
12+
let res
13+
for(let i = 0; i < n; i++) {
14+
if(leftSum[i] === sum - leftSum[i] - nums[i]) {
15+
res = i
16+
break
17+
}
18+
}
19+
20+
return res == null ? -1 : res
21+
};

0 commit comments

Comments
 (0)