LeetCode 0347. Top K Frequent Elements [first K-frequency element Python Medium] [] [] bucket sort
Problem
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.
problem
Given a non-null integer array, the frequency of occurrence of which the first returns the k higher element.
Example 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
Example 2:
输入: nums = [1], k = 1
输出: [1]
Description:
- You can always assume a given rational k, and 1 ≤ k ≤ number of different elements in the array.
- Your time complexity of the algorithm must be better than O ( the n-the n-log ), the n- array sizes.
Thinking
Bucket sort
- Frequency, the same element to element statistical occurrence count + 1.
- Then bucket sort, the elements in the array, in accordance with the frequency of occurrence packets, i.e. the frequency of occurrence of the presence of the i-th element i of the tub.
- Finally, before removing the reverse k elements from the bucket.
Time complexity : O (n)
space complexity : O (n)
Python code
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
# 统计元素的频率
count = dict()
for num in nums:
count[num] = count.get(num, 0) + 1 # 返回字典 count 中 num 元素对应的值, 没有就赋值为 0
# 桶排序
bucket = [[] for i in range(len(nums) + 1)]
for key, value in count.items():
bucket[value].append(key)
# 逆序取出前 k 个元素
res = list()
for i in range(len(nums), -1, -1): # 最后一个 -1 表示逆序
if bucket[i]:
res.extend(bucket[i]) # 在列表末尾追加元素
if len(res) >= k: # 只要前 k 个
break
return res[:k] # 输出第 k 个之前的元素(包括第 k 个元素)