nathanwailes

LeetCode 347 - Top K Frequent Elements - 2023.10.04 solution

Oct 3rd, 2023
1,317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. class Solution:
  2.     def topKFrequent(self, nums: List[int], k: int) -> List[int]:
  3.         """ If you had a dict mapping from each number to its count, along
  4.        with a variable containing the currently-most-common number, you could
  5.        step through the array, updating the dict and the variable as you go.
  6.        That would be o(n) time but also O(n) memory in the worst case (where
  7.        every number is different). That would be only to get the most-
  8.        frequent number.  If we wanted the two-most-frequent, we could use
  9.        two variables, or a list.
  10.  
  11.        The naive approach would be to just keep a dict of each num to its
  12.        count, then turn it into tuples and sort by the count, and step
  13.        through the sorted version to return the k-most-frequent. That would
  14.        I think be O(nlogn) in the worst case (where each number only appears
  15.        once).
  16.  
  17.        My thought now is: if we absolutely want O(n) time, how can we throw
  18.        more memory at the problem?
  19.        Another question I ask myself: what could we do with a second pass
  20.        through the input once we'd done our first pass and created that
  21.        dict, or what could we do by doing an iteration through the dict?
  22.  
  23.        Once we have the dict, we could create another list of the length of
  24.        the number of elements, step through the dict and add each number
  25.        to the index corresponding to its count.  Then we could do an
  26.        iteration backwards through that list to find the top k elements.
  27.        Finished planning / thinking at 14:07
  28.        """
  29.         num_to_count = defaultdict(int)
  30.         for n in nums:
  31.             num_to_count[n] += 1
  32.        
  33.         count_to_nums = [[] for i in range(len(nums))]
  34.         for n in num_to_count.keys():
  35.             count = num_to_count[n]
  36.             count_to_nums[count-1].append(n)
  37.  
  38.         top_k_elements = []
  39.         j = 0
  40.         for i in range(len(nums)-1, -1, -1):
  41.             if j == k:
  42.                 return top_k_elements
  43.             if len(count_to_nums[i]) > 0:
  44.                 top_k_elements.extend(count_to_nums[i])
  45.                 j += len(count_to_nums[i])
  46.         return top_k_elements
Advertisement
Add Comment
Please, Sign In to add comment