Skip to content

Commit 7a71b7a

Browse files
committed
add 374 solution
1 parent f260fcb commit 7a71b7a

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-
func Solution(x bool) bool {
4-
return x
3+
import "sort"
4+
5+
func topKFrequent(nums []int, k int) []int {
6+
tmp := make(map[int]int)
7+
res := []int{}
8+
s := [][]int{}
9+
// 统计每个字符出现次数
10+
for _, v := range nums {
11+
tmp[v]++
12+
}
13+
// 保存 数字/次数 映射 i,v 数字,次数
14+
for i, v := range tmp {
15+
s = append(s, []int{i, v})
16+
}
17+
// 按照次数排序
18+
sort.Slice(s, func(a, b int) bool {
19+
return s[a][1] > s[b][1]
20+
})
21+
// 截取前k个
22+
for i := 0; i < k; i++ {
23+
res = append(res, s[i][0])
24+
}
25+
return res
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
name string
13-
inputs bool
14-
expect bool
13+
input1 []int
14+
input2 int
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
for i, c := range cases {
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, with inputs: %v",
27-
c.expect, got, c.inputs)
26+
t.Fatalf("expected: %v, but got: %v, with input1: %v input2: %v",
27+
c.expect, got, c.input1, c.input2)
2828
}
2929
})
3030
}

0 commit comments

Comments
 (0)