From 6a6858b2e84f65ba24c684a76359b83337ff2955 Mon Sep 17 00:00:00 2001 From: baici1 <249337001@qq.com> Date: Thu, 2 Sep 2021 15:44:01 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20347.=E5=89=8D=20K=20?= =?UTF-8?q?=E4=B8=AA=E9=AB=98=E9=A2=91=E5=85=83=E7=B4=A0=20go=20=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E4=B8=A4=E4=B8=AA=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0347.前K个高频元素.md | 73 ++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) 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