Skip to content

Commit 2ef80ec

Browse files
committed
solve problem Find Pivot Index
1 parent c294cba commit 2ef80ec

File tree

5 files changed

+60
-0
lines changed

5 files changed

+60
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ All solutions will be accepted!
142142
|141|[Linked List Cycle](https://leetcode-cn.com/problems/linked-list-cycle/description/)|[java/py/js](./algorithms/LinkedListCycle)|Easy|
143143
|387|[First Unique Character In A String](https://leetcode-cn.com/problems/first-unique-character-in-a-string/description/)|[java/py/js](./algorithms/FirstUniqueCharacterInAString)|Easy|
144144
|628|[Maximum Product Of Three Numbers](https://leetcode-cn.com/problems/maximum-product-of-three-numbers/description/)|[java/py/js](./algorithms/MaximumProductOfThreeNumbers)|Easy|
145+
|724|[Find Pivot Index](https://leetcode-cn.com/problems/find-pivot-index/description/)|[java/py/js](./algorithms/FindPivotIndex)|Easy|
145146

146147
# Database
147148
|#|Title|Solution|Difficulty|

algorithms/FindPivotIndex/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Find Pivot Index
2+
This problem is easy to solve
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public int pivotIndex(int[] nums) {
3+
int totalSum = 0,
4+
leftSum = 0;
5+
6+
for (int num : nums) totalSum += num;
7+
8+
for (int i = 0; i < nums.length; i++) {
9+
if (leftSum == totalSum - nums[i] - leftSum) {
10+
return i;
11+
} else {
12+
leftSum += nums[i];
13+
}
14+
}
15+
16+
return -1;
17+
}
18+
}

algorithms/FindPivotIndex/solution.js

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var pivotIndex = function(nums) {
6+
let totalSum = 0,
7+
leftSum = 0
8+
9+
nums.forEach(num => totalSum += num)
10+
11+
for (let i = 0; i < nums.length; i++) {
12+
if (leftSum === totalSum - nums[i] - leftSum) {
13+
return i
14+
} else {
15+
leftSum += nums[i]
16+
}
17+
}
18+
19+
return -1
20+
};

algorithms/FindPivotIndex/solution.py

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution(object):
2+
def pivotIndex(self, nums):
3+
"""
4+
:type nums: List[int]
5+
:rtype: int
6+
"""
7+
total_sum = 0
8+
left_sum = 0
9+
10+
for num in nums:
11+
total_sum += num
12+
13+
for i in range(len(nums)):
14+
right_sum = total_sum - nums[i] - left_sum
15+
if left_sum == right_sum:
16+
return i
17+
left_sum += nums[i]
18+
19+
return -1

0 commit comments

Comments
 (0)