Add solution: top K frequent elements

This commit is contained in:
a.shalimov 2026-01-26 12:51:30 +03:00
parent 8689c3ab9d
commit 73e5d0cec2

View file

@ -0,0 +1,30 @@
from typing import List
from collections import defaultdict
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
res = []
count_elems = defaultdict(int)
count_in = { i: set() for i in range(0, len(nums) + 1) }
for i in range(0, len(nums)):
cur_char = nums[i]
count_elems[cur_char] += 1
tmp_value = count_elems[cur_char]
count_in[tmp_value].add(cur_char)
count_in[tmp_value - 1].discard(cur_char)
# Начинаем обход count_in с самого большого значения вхождений
for i in range(len(nums), 0, -1):
# Если есть элементы - записываем их в массив res
while len(count_in[i]) > 0:
res.append(count_in[i].pop())
# Уменьшаем значение k
k -=1
if k == 0:
return res
return res
cl = Solution()
print(cl.topKFrequent(nums=[1,1,1,2,2,3], k = 2))
print(cl.topKFrequent(nums=[1], k = 1))
print(cl.topKFrequent(nums = [1,2,1,2,1,2,3,1,3,2], k = 2))