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

Commit7a71b7a

Browse files
committed
add 374 solution
1 parentf260fcb commit7a71b7a

File tree

2 files changed

+31
-10
lines changed

2 files changed

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

3-
funcSolution(xbool)bool {
4-
returnx
3+
import"sort"
4+
5+
functopKFrequent(nums []int,kint) []int {
6+
tmp:=make(map[int]int)
7+
res:= []int{}
8+
s:= [][]int{}
9+
//统计每个字符出现次数
10+
for_,v:=rangenums {
11+
tmp[v]++
12+
}
13+
//保存 数字/次数 映射 i,v 数字,次数
14+
fori,v:=rangetmp {
15+
s=append(s, []int{i,v})
16+
}
17+
//按照次数排序
18+
sort.Slice(s,func(a,bint)bool {
19+
returns[a][1]>s[b][1]
20+
})
21+
//截取前k个
22+
fori:=0;i<k;i++ {
23+
res=append(res,s[i][0])
24+
}
25+
returnres
526
}

‎src/0347.Top-K-Frequent-Elements/Solution_test.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,21 +10,21 @@ func TestSolution(t *testing.T) {
1010
//测试用例
1111
cases:= []struct {
1212
namestring
13-
inputsbool
14-
expectbool
13+
input1 []int
14+
input2int
15+
expect []int
1516
}{
16-
{"TestCase",true,true},
17-
{"TestCase",true,true},
18-
{"TestCase",false,false},
17+
{"TestCase", []int{1,1,1,2,2,3},2, []int{1,2}},
18+
{"TestCase", []int{1},1, []int{1}},
1919
}
2020

2121
//开始测试
2222
fori,c:=rangecases {
2323
t.Run(c.name+" "+strconv.Itoa(i),func(t*testing.T) {
24-
got:=Solution(c.inputs)
24+
got:=topKFrequent(c.input1,c.input2)
2525
if!reflect.DeepEqual(got,c.expect) {
26-
t.Fatalf("expected: %v, but got: %v, withinputs: %v",
27-
c.expect,got,c.inputs)
26+
t.Fatalf("expected: %v, but got: %v, withinput1: %v input2: %v",
27+
c.expect,got,c.input1,c.input2)
2828
}
2929
})
3030
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp