Create top_k_frequent_heap.py

This commit is contained in:
Marina S 2023-07-30 19:43:59 -07:00 committed by GitHub
parent fa7c3cde66
commit f4e431412e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,17 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: bt3gl
def top_k_frequentnums: list[int], k: int) -> list[int]:
# O(1) time
if k == len(nums):
return nums
# 1. build a hashmap element: frequency
counter = Counter(nums)
# 2. build a heap of k most frequent elements
# 3. build an output array
# O(N log k) time
return heapq.nlargest(k, counter.keys(), key=counter.get)