Skip to content

Commit bc75371

Browse files
committed
Add: Find Pivot Index
1 parent 4d538bf commit bc75371

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -1 +1,17 @@
11
package find_pivot_index
2+
3+
func pivotIndex(nums []int) int {
4+
left, right := 0, 0
5+
for _, v := range nums {
6+
right += v
7+
}
8+
for i, v := range nums {
9+
right -= v
10+
if left == right {
11+
return i
12+
} else {
13+
left += v
14+
}
15+
}
16+
return -1
17+
}
Original file line numberDiff line numberDiff line change
@@ -1 +1,39 @@
11
package find_pivot_index
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
expected int
8+
}
9+
10+
func TestPivotIndex(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: []int{1, 7, 3, 6, 5, 6},
14+
expected: 3,
15+
},
16+
{
17+
input: []int{1, 2, 3},
18+
expected: -1,
19+
},
20+
{
21+
input: []int{0},
22+
expected: 0,
23+
},
24+
{
25+
input: []int{0, 0},
26+
expected: 0,
27+
},
28+
{
29+
input: []int{1, 2, 1},
30+
expected: 1,
31+
},
32+
}
33+
for _, tc := range tests {
34+
output := pivotIndex(tc.input)
35+
if output != tc.expected {
36+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
37+
}
38+
}
39+
}

0 commit comments

Comments
 (0)