8000 add 137 solution · zzti/awesome-golang-leetcode@c7500b4 · GitHub
[go: up one dir, main page]

Skip to content

Commit c7500b4

Browse files
committed
add 137 solution
1 parent a33b5ff commit c7500b4

File tree

2 files changed

+54
-8
lines changed

2 files changed

+54
-8
lines changed

src/0137.Single-Number-II/Solution.go

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,29 @@
11
package Solution
22

3-
func Solution(x bool) bool {
4-
return x
3+
func singleNumber(nums []int) int {
4+
m := make(map[int]int, len(nums))
5+
for _, v := range nums {
6+
m[v]++
7+
}
8+
for v := range m {
9+
if m[v] == 1 {
10+
return v
11+
}
12+
}
13+
return 0
14+
}
15+
16+
// 只循环一次
17+
// 3 ∗ (a+b+c)−(a+a+b+b+c) = 2 * c
18+
func singleNumber2(nums []int) int {
19+
m := make(map[int]int, len(nums))
20+
sum1, sum2 := 0, 0
21+
for _, v := range nums {
22+
if _, ok := m[v]; !ok {
23+
m[v]++
24+
sum1 += v
25+
}
26+
sum2 += v
27+
}
28+
return (3*sum1 - sum2) / 2
529
}

src/0137.Single-Number-II/Solution_test.go

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,40 @@ func TestSolution(t *testing.T) {
1010
// 测试用例
1111
cases := []struct {
1212
name string
13-
inputs bool
14-
expect bool
13+
inputs []int
14+
expect int
1515
}{
16-
{"TestCase", true, true},
17-
{"TestCase", true, true},
18-
{"TestCase", false, false},
16+
{"TestCase", []int{2, 2, 3, 2}, 3},
17+
{"TestCase", []int{0, 1, 0, 1, 0, 1, 99}, 99},
1918
}
2019

2120
// 开始测试
2221
for i, c := range cases {
2322
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
24-
got := Solution(c.inputs)
23+
got := singleNumber(c.inputs)
24+
if !reflect.DeepEqual(got, c.expect) {
25+
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
26+
c.expect, got, c.inputs)
27+
}
28+
})
29+
}
30+
}
31+
32+
func TestSolution2(t *testing.T) {
33+
// 测试用例
34+
cases := []struct {
35+
name string
36+
inputs []int
37+
expect int
38+
}{
39+
{"TestCase", []int{2, 2, 3, 2}, 3},
40+
{"TestCase", []int{0, 1, 0, 1, 0, 1, 99}, 99},
41+
}
42+
43+
// 开始测试
44+
for i, c := range cases {
45+
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
46+
got := singleNumber2(c.inputs)
2547
if !reflect.DeepEqual(got, c.expect) {
2648
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
2749
c.expect, got, c.inputs)

0 commit comments

Comments
 (0)
0