From 9707fbc521b16e79a43ef588e4f4a77454a30fdf Mon Sep 17 00:00:00 2001 From: Baturu <45113401+z80160280@users.noreply.github.com> Date: Wed, 2 Jun 2021 02:41:59 -0700 Subject: [PATCH] =?UTF-8?q?Update=200347.=E5=89=8DK=E4=B8=AA=E9=AB=98?= =?UTF-8?q?=E9=A2=91=E5=85=83=E7=B4=A0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0347.前K个高频元素.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 841584b4..71af618e 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -162,7 +162,33 @@ class Solution { Python: - +```python +#时间复杂度:O(nlogk) +#空间复杂度:O(n) +import heapq +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + #要统计元素出现频率 + map_ = {} #nums[i]:对应出现的次数 + for i in range(len(nums)): + map_[nums[i]] = map_.get(nums[i], 0) + 1 + + #对频率排序 + #定义一个小顶堆,大小为k + pri_que = [] #小顶堆 + + #用固定大小为k的小顶堆,扫面所有频率的数值 + for key, freq in map_.items(): + heapq.heappush(pri_que, (freq, key)) + if len(pri_que) > k: #如果堆的大小大于了K,则队列弹出,保证堆的大小一直为k + heapq.heappop(pri_que) + + #找出前K个高频元素,因为小顶堆先弹出的是最小的,所以倒叙来输出到数组 + result = [0] * k + for i in range(k-1, -1, -1): + result[i] = heapq.heappop(pri_que)[1] + return result +``` Go: