algos_and_structures/algocode/hash_tables/top_k_frequent_elements.py
2026-01-26 12:51:30 +03:00

30 lines
1.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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))