Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic1:
- use a map and store frequency of each element.make a min heap of k size.
- push elements from map to min heap where first element should be frequency
- and second element as elements that sorting happen on the basis of first element.
- while pushing compare top elememt of min heap with current element of map,if current
- element frequency is greater than top element,remove the top element and push current
- element else continue.
- finally all element of heap is the answer.
- Logic2:
- 1.Count the frequency of each element using a Python dictionary.
- 2.Create a list of empty lists where index represent frequency and list is used because multiple elements can have same freq.
- 3.Insert each element into the list at its frequency index.
- 4.Traverse this list from highest index to lowest.
- 5.Collect elements until k most frequent elements are obtained.*/
- from typing import List
- class Solution:
- def topKFrequent(self, arr: List[int], k: int) -> List[int]:
- freq_map = {}
- _max = 0
- ans = []
- # frequency map
- for num in arr:
- freq_map[num] = freq_map.get(num, 0) + 1
- _max = max(_max, freq_map[num])
- # bucket array (list of lists)
- freq = [[] for _ in range(_max + 1)]
- for num, count in freq_map.items():
- freq[count].append(num)
- # traverse from highest frequency
- for i in range(_max, 0, -1):
- for num in freq[i]:
- ans.append(num)
- if len(ans) == k:
- return ans
- return ans
Advertisement
Add Comment
Please, Sign In to add comment