Skip to content

Commit bfabbcb

Browse files
committed
feat: solution for 0724
1 parent 38832b6 commit bfabbcb

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

724.find-pivot-index.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
* @lc app=leetcode id=724 lang=cpp
3+
*
4+
* [724] Find Pivot Index
5+
*/
6+
7+
// @lc code=start
8+
class Solution {
9+
public:
10+
int pivotIndex(vector<int>& nums) {
11+
// explain the codes below:
12+
int sum = 0; // sum of all numbers before the pivot
13+
// sum of all numbers after the pivot
14+
for (int i = 0; i < nums.size(); i++) {
15+
sum += nums[i];
16+
}
17+
int left = 0; // sum of all numbers before the pivot
18+
for (int i = 0; i < nums.size(); i++) {
19+
// if the sum of all numbers before the pivot is equal to the sum of all numbers after the pivot, then the pivot is at index i
20+
if (left == sum - left - nums[i]) {
21+
return i;
22+
}
23+
left += nums[i];
24+
}
25+
return -1;
26+
27+
}
28+
};
29+
// @lc code=end
30+

0 commit comments

Comments
 (0)