Q:
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2]
示例 2:
输入: nums = [1], k = 1 输出: [1]
链接:https://leetcode-cn.com/problems/top-k-frequent-elements/description/
思路:统计字符频,排序,输出
代码:
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
from collections import Counter
dic = Counter(nums)
tmp = [(v,dic[v]) for v in dic]
tmp.sort(key=lambda tmp: tmp[1],reverse=True)
res = [tmp[i][0] for i in range(k)]
return res