Skip to content

Commit 82a99e3

Browse files
committed
724. Find Pivot Index
1 parent a4f7f5e commit 82a99e3

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

find-pivot-index/Readme.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# 724. Find Pivot Index
2+
3+
Given an array of integers nums, write a method that returns the "pivot" index of this array.
4+
5+
We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
6+
7+
If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.
8+
9+
## Example 1
10+
11+
```go
12+
Input:
13+
nums = [1, 7, 3, 6, 5, 6]
14+
Output: 3
15+
Explanation:
16+
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
17+
Also, 3 is the first index where this occurs.
18+
```
19+
20+
## Example 2
21+
22+
```go
23+
Input:
24+
nums = [1, 2, 3]
25+
Output: -1
26+
Explanation:
27+
There is no index that satisfies the conditions in the problem statement.
28+
```

find-pivot-index/main.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package leetcode
2+
3+
func pivotIndex(nums []int) int {
4+
sum := 0
5+
for _, x := range nums {
6+
sum = sum + x
7+
}
8+
leftsum := 0
9+
for i, y := range nums {
10+
if leftsum == sum-leftsum-y {
11+
return i
12+
}
13+
leftsum = leftsum + y
14+
}
15+
return -1
16+
}

find-pivot-index/main_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package leetcode
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
func TestPivotIndex(t *testing.T) {
9+
nums := []int{1, 7, 3, 6, 5, 6}
10+
i := pivotIndex(nums)
11+
if i != 3 {
12+
t.Log(fmt.Sprintf("expected %d, but got %d", 3, i))
13+
t.FailNow()
14+
}
15+
16+
}

0 commit comments

Comments
 (0)