From 40b392588699b33a750101ab63adbb3b6f4f6860 Mon Sep 17 00:00:00 2001 From: OrangeLiuSSE <143183385+OrangeLiuSSE@users.noreply.github.com> Date: Thu, 7 Mar 2024 10:45:09 +0800 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 | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 93d605f5..b340e185 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -218,7 +218,7 @@ class Solution { ``` ### Python: - +解法一: ```python #时间复杂度:O(nlogk) #空间复杂度:O(n) @@ -246,6 +246,31 @@ class Solution: result[i] = heapq.heappop(pri_que)[1] return result ``` +解法二: +```python +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + # 使用字典统计数字出现次数 + time_dict = defaultdict(int) + for num in nums: + time_dict[num] += 1 + # 更改字典,key为出现次数,value为相应的数字的集合 + index_dict = defaultdict(list) + for key in time_dict: + index_dict[time_dict[key]].append(key) + # 排序 + key = list(index_dict.keys()) + key.sort() + result = [] + cnt = 0 + # 获取前k项 + while key and cnt != k: + result += index_dict[key[-1]] + cnt += len(index_dict[key[-1]]) + key.pop() + + return result[0: k] +``` ### Go: