nathanwailes

LeetCode 347 - Top K Frequent Elements - 2022.12.29 solution

Dec 29th, 2022
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. class Solution:
  2.     def topKFrequent(self, nums: List[int], k: int) -> List[int]:
  3.         # How to solve it: we could add the elements to a dict, then sort by the counts
  4.         # and return the top k ones, but that would be O(n log n) in the worst case.
  5.         # To do better, we can create a list the size of the input list, add the items
  6.         # from the count dict to the position in the list corresponding to the count,
  7.         # and then go through the list starting from the right.  That should be O(n)
  8.         # in the worst case.
  9.         count_dict = defaultdict(int)
  10.         for num in nums:
  11.             count_dict[num] += 1
  12.        
  13.         counts_list = [[] for i in range(len(nums) + 1)]
  14.         for num, count in count_dict.items():
  15.             counts_list[count].append(num)
  16.        
  17.         res = []
  18.         for i in range(len(counts_list)-1, -1, -1):
  19.             if len(res) == k:
  20.                 break
  21.             else:
  22.                 res.extend(counts_list[i])
  23.         return res
Advertisement
Add Comment
Please, Sign In to add comment