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
相关推荐
Hesionberger9 小时前
LeetCode406:重建身高队列精髓解析
开发语言·数据结构·python·算法·leetcode
卡提西亚10 小时前
leetcode-239. 滑动窗口最大值
算法·leetcode·职场和发展
旖-旎11 小时前
LeetCode 494:目标和(动态规划/01背包问题)—— 题解
c++·算法·leetcode·动态规划·01背包
圣保罗的大教堂18 小时前
leetcode 3867. 数对的最大公约数之和 中等
leetcode
To_OC20 小时前
LC 15 三数之和:双指针不难,难的是把去重做对
javascript·算法·leetcode
G.O.G.O.G1 天前
LeetCode SQL 从入门到精通(MySQL)06(上)
数据库·sql·mysql·leetcode
闪电悠米1 天前
力扣hot100-56.合并区间-排序详解
数据结构·算法·leetcode·贪心算法·排序算法
卡提西亚1 天前
leetcode-1438. 绝对差不超过限制的最长连续子数组
算法·leetcode·职场和发展
Java面试题总结1 天前
LeetCode 93.复原IP地址
算法·leetcode·职场和发展·.net
Tisfy1 天前
LeetCode 3867.数对的最大公约数之和:按题目说的做(gcd)
算法·leetcode·题解·模拟·最大公约数·gcd