用字典存每一个数字出现的次数,作为value值,然后根据value值进行排序,取前k个
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
zd = {}
for n in nums:
if n not in zd:
zd[n] = 1
else:
zd[n] += 1
l = sorted(zd, key=lambda x:zd[x], reverse = True)
res = []
for key in l:
res.append(key)
k -= 1
if k == 0:
break
return res
网友评论