nathanwailes

Top k most-frequent elements

Jun 10th, 2024
346
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.27 KB | None | 0 0
  1. """
  2. """
  3. import heapq
  4. from collections import Counter
  5.  
  6. def top_k_frequent(nums, k):
  7.     count = Counter(nums)
  8.     return heapq.nlargest(k, count.keys(), key=count.get)
  9.  
  10. # Example usage
  11. nums = [1, 1, 1, 2, 2, 3]
  12. k = 2
  13. print(top_k_frequent(nums, k))  # Output: [1, 2]
  14.  
Advertisement
Add Comment
Please, Sign In to add comment