python 前 k 个高频元素
时间: 2024-05-05 21:17:25 浏览: 96
MangoDowner#clear-leetcode#692.前K个高频单词1
可以使用 Counter 对列表中的元素进行统计,然后使用堆排序找出前 k 个高频元素。
具体实现如下:
```python
from collections import Counter
import heapq
def top_k_frequent(nums, k):
counter = Counter(nums)
heap = []
for num, freq in counter.items():
if len(heap) < k:
heapq.heappush(heap, (freq, num))
else:
if freq > heap[0][0]:
heapq.heappop(heap)
heapq.heappush(heap, (freq, num))
res = []
while heap:
res.insert(0, heapq.heappop(heap)[1])
return res
```
示例:
```python
>>> nums = [1, 1, 1, 2, 2, 3]
>>> top_k_frequent(nums, 2)
[1, 2]
```
阅读全文