347. 前 K 个高频元素
1 暴力计数+排序 O(nlogn)
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = collections.defaultdict(int)
for val in nums:
count[val] += 1
return sorted(count.keys(), key = lambda x : count[x], reverse = True)[:k]
2 堆 O(nlogk)
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
heap = []
count = collections.defaultdict(int)
for num in nums:
count[num] += 1
for key, val in count.items():
if len(heap) < k:
# remember to change the order
heappush(heap, (val, key))
elif val > heap[0][0]:
heapreplace(heap, (val, key))
return [_[1] for _ in heap]