Movatterモバイル変換


[0]ホーム

URL:


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

Commitc7500b4

Browse files
committed
add 137 solution
1 parenta33b5ff commitc7500b4

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-
funcSolution(xbool)bool {
4-
returnx
3+
funcsingleNumber(nums []int)int {
4+
m:=make(map[int]int,len(nums))
5+
for_,v:=rangenums {
6+
m[v]++
7+
}
8+
forv:=rangem {
9+
ifm[v]==1 {
10+
returnv
11+
}
12+
}
13+
return0
14+
}
15+
16+
//只循环一次
17+
// 3 ∗ (a+b+c)−(a+a+b+b+c) = 2 * c
18+
funcsingleNumber2(nums []int)int {
19+
m:=make(map[int]int,len(nums))
20+
sum1,sum2:=0,0
21+
for_,v:=rangenums {
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
namestring
13-
inputsbool
14-
expectbool
13+
inputs[]int
14+
expectint
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
fori,c:=rangecases {
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+
funcTestSolution2(t*testing.T) {
33+
//测试用例
34+
cases:= []struct {
35+
namestring
36+
inputs []int
37+
expectint
38+
}{
39+
{"TestCase", []int{2,2,3,2},3},
40+
{"TestCase", []int{0,1,0,1,0,1,99},99},
41+
}
42+
43+
//开始测试
44+
fori,c:=rangecases {
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)

[8]ページ先頭

©2009-2025 Movatter.jp