Skip to content

Instantly share code, notes, and snippets.

@pyrofolium
Last active April 27, 2020 18:54
Show Gist options
  • Select an option

  • Save pyrofolium/e5d33b662d503fd36d9d2e8867922b13 to your computer and use it in GitHub Desktop.

Select an option

Save pyrofolium/e5d33b662d503fd36d9d2e8867922b13 to your computer and use it in GitHub Desktop.
def topKFrequent(nums: List[int], k: int) -> List[int]:
freq_by_num = {}
max_freq = float("-inf")
for num in nums:
freq_by_num[num] = freq_by_num[num] + 1 if num in freq_by_num else 1
max_freq = max(max_freq, freq_by_num[num])
nums_by_freq = {}
for num, freq in freq_by_num.items():
nums_by_freq[freq] = nums_by_freq[freq] + [num] if freq in nums_by_freq else [num]
return [j for i in range(max_freq+1) if i in nums_by_freq for j in nums_by_freq[i]][-k:]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment