347. 前 K 个高频元素

图片.png

小顶堆

  1. package main
  2. import (
  3. "container/heap"
  4. "fmt"
  5. )
  6. type Node struct {
  7. Val int
  8. Num int
  9. }
  10. type NodeHeap []*Node
  11. func(h NodeHeap)Len()int{
  12. return len(h)
  13. }
  14. func(h NodeHeap)Swap(i,j int){
  15. h[i],h[j] = h[j],h[i]
  16. }
  17. func(h NodeHeap)Less(i,j int)bool{
  18. return h[i].Num<h[j].Num
  19. }
  20. func(h *NodeHeap)Push(x interface{}){
  21. *h = append(*h,x.(*Node))
  22. }
  23. func (h *NodeHeap)Pop()interface{} {
  24. x :=(*h)[len(*h)-1]
  25. *h =(*h)[:len(*h)-1]
  26. return x
  27. }
  28. func min(a,b int)int{
  29. if a<b{
  30. return a
  31. }
  32. return b
  33. }
  34. func topKFrequent(nums []int, k int) []int {
  35. m :=make(map[int]int)
  36. for _,v :=range nums{
  37. m[v]++
  38. }
  39. topK :=min(k,len(m))
  40. size :=0
  41. h :=&NodeHeap{}
  42. for k,v :=range m{
  43. n := &Node{
  44. Val: k,
  45. Num: v,
  46. }
  47. if size<topK{
  48. heap.Push(h,n)
  49. size++
  50. }else {
  51. if v >(*h)[0].Num{
  52. heap.Pop(h)
  53. heap.Push(h,n)
  54. }
  55. }
  56. }
  57. var res []int
  58. for i:=0;i<topK;i++{
  59. res = append(res,heap.Pop(h).(*Node).Val)
  60. }
  61. return res
  62. }
  63. func main() {
  64. fmt.Println(topKFrequent([]int{1,1,1,2,2,3},2)) //1,2
  65. fmt.Println(topKFrequent([]int{1},1))
  66. }

图片.png