Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2518b37

Browse files
author
Shuo
authored
Merge pull request #566 from openset/develop
Add: Last Stone Weight
2 parents 86cd741 + 5309dc7 commit 2518b37

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package last_stone_weight
2+
3+
import "sort"
4+
5+
func lastStoneWeight(stones []int) int {
6+
for len(stones) >= 2 {
7+
n := len(stones) - 1
8+
sort.Ints(stones)
9+
v := stones[n] - stones[n-1]
10+
if v > 0 {
11+
stones[n-1] = v
12+
} else {
13+
n--
14+
}
15+
stones = stones[:n]
16+
}
17+
stones = append(stones, 0)
18+
return stones[0]
19+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package last_stone_weight
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
expected int
8+
}
9+
10+
func TestLastStoneWeight(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: []int{2, 7, 4, 1, 8, 1},
14+
expected: 1,
15+
},
16+
{
17+
input: []int{2, 7, 4, 1, 8, 1, 5},
18+
expected: 0,
19+
},
20+
{
21+
input: []int{316, 157, 73, 106, 771, 828},
22+
expected: 37,
23+
},
24+
}
25+
for _, tc := range tests {
26+
output := lastStoneWeight(tc.input)
27+
if output != tc.expected {
28+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
29+
}
30+
}
31+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /