diff --git a/top_k_frequent.py b/top_k_frequent.py new file mode 100644 index 0000000..4f62d3f --- /dev/null +++ b/top_k_frequent.py @@ -0,0 +1,10 @@ +from collections import Counter +import heapq + +def top_k_frequent(nums, k): + freq = Counter(nums) + return [item for item, _ in heapq.nlargest(k, freq.items(), key=lambda x: x[1])] + +nums = [1, 1, 2, 2, 3] +k = 2 +print(top_k_frequent(nums, k))