题目
给定数组和k,求数组中出现频率最高的前k个元素,答案唯一。
自练代码
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
rank = {}
for i in nums:
if i not in rank:
rank[i] = 1
else:
rank[i] += 1
tmp = sorted(rank.items(), key = lambda item: item[1], reverse = True)
ans = []
for i in tmp[:k]:
ans.append(i[0])
return(ans)
结果
执行用时: 64 ms , 在所有 Python3 提交中击败了24.52% 的用户
内存消耗:16.6 MB , 在所有 Python3 提交中击败了36.77% 的用户