Skip to content

Commit 51f59c6

Browse files
committed
feat: add find pivot index
1 parent 06198ab commit 51f59c6

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

js/pivot_index.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2022-05-14 15:07:38
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2022-05-14 15:08:47
6+
*/
7+
/**
8+
* 来源:https://leetcode-cn.com/problems/find-pivot-index/
9+
*
10+
* 724. 寻找数组的中心下标
11+
*
12+
* 给你一个整数数组 nums ,请计算数组的 中心下标 。数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。
13+
* 如果中心下标位于数组最左端,那么左侧数之和视为 0 ,因为在下标的左侧不存在元素。这一点对于中心下标位于数组最右端同样适用。
14+
* 如果数组有多个中心下标,应该返回 最靠近左边 的那一个。如果数组不存在中心下标,返回 -1 。
15+
*
16+
*/
17+
18+
const pivotIndex = (nums) => {
19+
let total = nums.reduce((ret, num) => ret + num, 0);
20+
let sum = 0;
21+
22+
for (let i = 0, len = nums.length; i < len; i++) {
23+
if (sum * 2 + nums[i] === total) {
24+
return i;
25+
}
26+
27+
sum += nums[i];
28+
}
29+
30+
return -1;
31+
};

0 commit comments

Comments
 (0)