mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Update and rename top_k_frequent_heap.py to top_k_frequent.py
This commit is contained in:
parent
e7d19505dc
commit
bf35809bb2
13
heaps/top_k_frequent.py
Normal file
13
heaps/top_k_frequent.py
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# author: bt3gl
|
||||||
|
|
||||||
|
|
||||||
|
def top_k_frequent_values(list, k):
|
||||||
|
|
||||||
|
if k == len(nums):
|
||||||
|
return nums
|
||||||
|
|
||||||
|
# hashmap element: frequency
|
||||||
|
counter = Counter(nums)
|
||||||
|
return heapq.nlargest(k, counter.keys(), key=counter.get)
|
@ -1,17 +0,0 @@
|
|||||||
#!/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)
|
|
Loading…
x
Reference in New Issue
Block a user