topic
https://leetcode-cn.com/problems/top-k-frequent-elements/
Given a non-empty array of integers, return the element with the highest k before its frequency.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Description:
You can assume that a given k is always reasonable, and 1 ≤ k ≤ the number of different elements in the array.
The time complexity of your algorithm must be better than O (n log n), where n is the size of the array.
Problem-solving ideas
- bucket sorting
- Scan the array first to get the digital frequency table
- Then construct a dictionary like {frequency: [number]}, which is called a bucket
- In the previous step, get the maximum frequency
max_f
- From
max_f
to0
reverse cycle, according to the meaning of the question, no need to consider abnormal conditions, the whole bucket is added to the result list - Exit until the length of the result list meets k
Code
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# - statistic frequency
freq_dict = defaultdict(int)
for n in nums:
freq_dict[n] += 1
# - assign buckets, format is {freq:[number]}
bucket_dict = defaultdict(list)
max_f = 0
for n,f in freq_dict.items():
bucket_dict[f].append(n)
max_f = max(max_f, f)
# - reverse traverse
res = []
for f in range(max_f,0,-1):
if f in bucket_dict:
res += bucket_dict[f]
if len(res) >= k:
return res