Skip to content

Commit 3b2a118

Browse files
Merge pull request youngyangyang04#707 from baici1/master
增加 347.前 K 个高频元素 go 版本两个解法
2 parents e856802 + 6a6858b commit 3b2a118

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

problems/0347.前K个高频元素.md

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,79 @@ class Solution:
189189

190190
Go:
191191

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+
192265

193266
javaScript:
194267
```js

0 commit comments

Comments
 (0)