Skip to content

Commit d04ad3f

Browse files
committed
Add solution #724
1 parent 8e079a7 commit d04ad3f

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@
233233
706|[Design HashMap](./0706-design-hashmap.js)|Easy|
234234
713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium|
235235
722|[Remove Comments](./0722-remove-comments.js)|Medium|
236+
724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy|
236237
733|[Flood Fill](./0733-flood-fill.js)|Easy|
237238
739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium|
238239
746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy|

solutions/0724-find-pivot-index.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* 724. Find Pivot Index
3+
* https://leetcode.com/problems/find-pivot-index/
4+
* Difficulty: Easy
5+
*
6+
* Given an array of integers nums, calculate the pivot index of this array.
7+
*
8+
* The pivot index is the index where the sum of all the numbers strictly to the left
9+
* of the index is equal to the sum of all the numbers strictly to the index's right.
10+
*
11+
* If the index is on the left edge of the array, then the left sum is 0 because there
12+
* are no elements to the left. This also applies to the right edge of the array.
13+
*
14+
* Return the leftmost pivot index. If no such index exists, return -1.
15+
*/
16+
17+
/**
18+
* @param {number[]} nums
19+
* @return {number}
20+
*/
21+
var pivotIndex = function(nums) {
22+
let left = 0;
23+
let right = nums.reduce((sum, n) => sum + n, 0);
24+
25+
for (let i = 0; i < nums.length; i++) {
26+
left += nums[i];
27+
right -= nums[i];
28+
if (left - nums[i] === right) {
29+
return i;
30+
}
31+
}
32+
33+
return -1;
34+
};

0 commit comments

Comments
 (0)