题目描述:
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
示例:
1) 输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
2) 输入: nums = [1], k = 1
输出: [1]
思路:
使用优先队列,在统计好每个元素出现的顺序以后,小顶堆存放元组进行排序,(a,b)按照a进行排序即可。
import heapq
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
# 使用优先队列:
a = []
heapq.heapify(a)
count = collections.Counter(nums)
for key, value in count.items():
heapq.heappush(a, (value, key)) # (value, key) 哪一个在前按照哪一个排序
if len(a) > k:
heapq.heappop(a)
return [item[1] for item in a]
解释一下collections.Counter(nums):直接将一个list传入Counter中作为参数,它会自动为我们替当中的每个元素计数。
words = ['apple', 'apple', 'pear', 'watermelon', 'pear', 'peach']
from collections import Counter
counter = Counter(words)
>>> print(counter)
Counter({'apple': 2, 'pear': 2, 'watermelon': 1, 'peach': 1}
在本题代码中,若不调用函数实现统计的话,也可以自己写一个字典进行实现:
count_1 = {}
for i in nums:
if i in count_1.keys():
count_1[i] = count_1.get(i) + 1
else:
count_1[i] = 1
print(count_1)