diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 54be5cc4..6012e118 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -189,6 +189,79 @@ class Solution: Go: +```go +//方法一:小顶堆 +func topKFrequent(nums []int, k int) []int { + map_num:=map[int]int{} + //记录每个元素出现的次数 + for _,item:=range nums{ + map_num[item]++ + } + h:=&IHeap{} + heap.Init(h) + //所有元素入堆,堆的长度为k + for key,value:=range map_num{ + heap.Push(h,[2]int{key,value}) + if h.Len()>k{ + heap.Pop(h) + } + } + res:=make([]int,k) + //按顺序返回堆中的元素 + for i:=0;imap_num[ans[b]] + }) + return ans[:k] +} +``` + + + javaScript: ```js