python 前 k 个高频元素
时间: 2024-05-05 10:17:25 浏览: 99
可以使用 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]
```
相关问题
用python 前k个高频元素
可以使用Python内置的Counter模块来实现,代码如下:
```python
from collections import Counter
def topKFrequent(nums, k):
freq = Counter(nums)
return [x[0] for x in freq.most_common(k)]
```
其中,nums为输入的列表,k为需要输出的前k个高频元素的个数,返回一个列表,包含前k个高频元素。
阅读全文