File tree Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change @@ -189,6 +189,79 @@ class Solution:
189
189
190
190
Go:
191
191
192
+ ``` go
193
+ // 方法一:小顶堆
194
+ func topKFrequent (nums []int , k int ) []int {
195
+ map_num := map [int ]int {}
196
+ // 记录每个元素出现的次数
197
+ for _,item := range nums{
198
+ map_num[item]++
199
+ }
200
+ h := &IHeap{}
201
+ heap.Init (h)
202
+ // 所有元素入堆,堆的长度为k
203
+ for key,value := range map_num{
204
+ heap.Push (h,[2 ]int {key,value})
205
+ if h.Len ()>k{
206
+ heap.Pop (h)
207
+ }
208
+ }
209
+ res := make ([]int ,k)
210
+ // 按顺序返回堆中的元素
211
+ for i := 0 ;i<k;i++{
212
+ res[k-i-1 ]=heap.Pop (h).([2 ]int )[0 ]
213
+ }
214
+ return res
215
+ }
216
+
217
+ // 构建小顶堆
218
+ type IHeap [][2 ]int
219
+
220
+ func (h IHeap ) Len ()int {
221
+ return len (h)
222
+ }
223
+
224
+ func (h IHeap ) Less (i,j int) bool {
225
+ return h[i][1 ]<h[j][1 ]
226
+ }
227
+
228
+ func (h IHeap ) Swap (i ,j int ) {
229
+ h[i],h[j]=h[j],h[i]
230
+ }
231
+
232
+ func (h *IHeap ) Push (x interface {}){
233
+ *h=append (*h,x.([2 ]int ))
234
+ }
235
+ func (h *IHeap ) Pop () interface {}{
236
+ old := *h
237
+ n := len (old)
238
+ x := old[n-1 ]
239
+ *h=old[0 :n-1 ]
240
+ return x
241
+ }
242
+
243
+
244
+ // 方法二:利用O(logn)排序
245
+ func topKFrequent (nums []int , k int ) []int {
246
+ ans := []int {}
247
+ map_num := map [int ]int {}
248
+ for _,item := range nums {
249
+ map_num[item]++
250
+ }
251
+ for key,_ := range map_num{
252
+ ans=append (ans,key)
253
+ }
254
+ // 核心思想:排序
255
+ // 可以不用包函数,自己实现快排
256
+ sort.Slice (ans,func (a,b int )bool {
257
+ return map_num[ans[a]]>map_num[ans[b]]
258
+ })
259
+ return ans[:k]
260
+ }
261
+ ```
262
+
263
+
264
+
192
265
193
266
javaScript:
194
267
``` js
You can’t perform that action at this time.
0 commit comments