Merge pull request #2464 from OrangeLiuSSE/patch-1

Update 0347.前K个高频元素.md
This commit is contained in:
程序员Carl
2024-04-07 10:24:28 +08:00
committed by GitHub

View File

@ -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