Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7512ef3

Browse files
committed
added: top k frequent elements
1 parent cdd069f commit 7512ef3

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# top k frequency elements | leetcode 347 | https://leetcode.com/problems/top-k-frequent-elements/
2+
# use buckets with each bucket being the frequency of an element
3+
4+
from collections import Counter
5+
6+
class Solution:
7+
def topKFrequent(self, nums: list[int], k: int) -> list[int]:
8+
freq = Counter(nums)
9+
N = len(nums)
10+
11+
# create buckets where index = frequency of element
12+
buckets = [[] for x in range(N + 1)]
13+
for f in freq:
14+
buckets[freq[f]].append(f)
15+
16+
# get k elements starting from the end of the bucket
17+
k_mf = []
18+
for x in buckets[::-1]:
19+
if k > 0:
20+
if x != []:
21+
k_mf += x
22+
k -= len(x)
23+
else:
24+
return k_mf
25+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /