leetcode hot100 347. 前 K 个高频元素 medium 桶排序


频率前 k 高的元素

时间复杂度:O(n)

空间复杂度:O(n)

python 复制代码
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        
        # 1.用哈希表统计频率
        count = Counter(nums)
        #print(count.items())   # dict_items([(1, 3), (2, 2), (3, 1)])  (num, freqs)

        #2. 创建一个长度为 n+1 的空数组(桶数组)
        n = len(nums)
        buckets = [[]  for _ in range(n+1)]

        # 索引= 出现频率
        for num, freqs in count.items():
            buckets[freqs].append(num)   # 向每个频率的空列表中,加入对应的num值

        #注意: 每个桶里可能有多个数字,buckets[2] = [1, 2] → 频率为 2 的数字有两个,分别是1和2
        
        # 从最高频开始,把元素加入res,直到加入k个(频率前 k 高的元素)
        res = []
        for freq in range(n, 0, -1):  # 从最高频开始,num加入res
            for num in buckets[freq]:
                res.append(num)

                if len(res) == k:
                    return res
相关推荐
Navigator_Z1 天前
LeetCode //C - 1250. Check If It Is a Good Array
c语言·算法·leetcode
圣保罗的大教堂1 天前
leetcode 3483. 不同三位偶数的数目 简单
leetcode
mmmmath_31 天前
LeetCode.018.四数之和
数据结构·算法·leetcode
圣保罗的大教堂1 天前
leetcode 836. 矩形重叠 简单
leetcode
土司大王1 天前
LeetCode hot100——394.字符串解码:Java 双栈模拟
java·算法·leetcode
a187927218311 天前
【算法】双指针与滑动窗口(三):相向双指针——比较、排除、收缩
算法·leetcode·双指针·滑动窗口·原理·相向双指针·算法讲解
6Hzlia2 天前
【Classic 150 刷题计划】 LeetCode 14. 最长公共前缀 | C++ 纵向扫描法与防越界细节
c++·算法·leetcode
Tisfy2 天前
LeetCode 0836.矩形重叠:xy两方向分别看
数学·leetcode·题解·模拟
青山木2 天前
Hot 100 --- 最长递增子序列
java·数据结构·算法·leetcode·动态规划
土司大王2 天前
LeetCode hot100——33.搜索旋转排序数组:Java 二分模板与 O(log n) 实现
数据结构·算法·leetcode