Top K Frequent Elements
Medium
Subject: Heap / Priority Queue
Time Complexity
O(N log K)
Space Complexity
O(N + K)
Problem Description
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Optimal Solution
Pythonfrom collections import Counter
import heapq
def topKFrequent(nums, k):
count = Counter(nums)
return [num for num, _ in heapq.nlargest(k, count.items(), key=lambda x: x[1])]