给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/top-k-frequent-elements
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
from collections import Counter
from typing import List
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
dic2 = dict(Counter(nums))
sort = sorted(dic2.items(), key=lambda e: e[1], reverse=True)
res = []
for i in range(k):
res.append(sort[i][0])
return res
if __name__ == "__main__":
s = Solution()
list2 = [-1,-1]
k =1 #
print(s.topKFrequent(list2, k))