class Solution:
def __init__(self):
self.alldict = {}
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
for each in nums:
if each in self.alldict:
self.alldict[each] += 1
else:
self.alldict[each] = 1
sorted_dict = sorted(self.alldict.items(),key=lambda x:x[1],reverse=True)
res = []
index = 0
for _,re in enumerate(sorted_dict):
res.append(re[0])
index += 1
if index == k:
break
return res
Leetcode刷题记录——347. 前 K 个高频元素
最新推荐文章于 2024-06-20 16:39:31 发布