思路一:库函数(一行)
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
return [item[0] for item in collections.Counter(nums).most_common(k)]
思路二:堆
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
from collections import defaultdict, Counter
import heapq
lookup = Counter(nums)
heap = []
for ky, vl in lookup.items():
heapq.heappush(heap, [-vl, ky])
res = []
for _ in range(k):
res.append(heapq.heappop(heap)[1])
return res
简单写法
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
import heapq
c = collections.Counter(nums)
return heapq.nlargest(k, c, key=lambda x: c[x] )
思路三:桶排序
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
from collections import Counter
c = Counter(nums)
buckets = [[] for _ in range(len(nums) + 1)]
for x, y in c.items():
buckets[y].append(x)
res = []
for i in range(len(nums), -1, -1):
if len(res) > k:
break
res.extend(buckets[i])
return res[:k]