diff --git a/algocode/hash_tables/top_k_frequent_elements.py b/algocode/hash_tables/top_k_frequent_elements.py new file mode 100644 index 0000000..c6013fd --- /dev/null +++ b/algocode/hash_tables/top_k_frequent_elements.py @@ -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)) +