给你一个整数数组 nums
和一个整数 k
,请你返回其中出现频率前 k
高的元素。你可以按 任意顺序 返回答案。
使用了Counter函数统计数字出现的频率。
from collections import Counter
class Solution(object):
def topKFrequent(self, nums, k):
result = []
count = Counter(nums)
sorted_count = sorted(count.items(),key=lambda x:x[1],reverse=True)
for item in sorted_count[:k]:
result.append(item[0])
return result