Skip to content

Commit feb2dc0

Browse files
committed
top-k-frequent-elements solution
1 parent 1d47595 commit feb2dc0

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution:
2+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
3+
nums.sort()
4+
items = {}
5+
n = nums[0]
6+
cnt = 1
7+
if len(nums) > 1:
8+
for i in range(1, len(nums)):
9+
if n != nums[i]:
10+
items[n] = cnt
11+
n = nums[i]
12+
cnt = 1
13+
else:
14+
cnt += 1
15+
items[n] = cnt
16+
else:
17+
items[n] = 1
18+
sorted_items_desc = sorted(items.items(), key=lambda item: item[1], reverse=True)
19+
result = []
20+
for i in sorted_items_desc[:k]:
21+
result.append(i[0])
22+
return result

0 commit comments

Comments
 (0)