You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode 347:Top K Frequent Elements双值输入代码异常排查

问题描述

我的代码在处理仅包含两个值的输入时无法正常工作,处理两个以上值的输入则能正确创建字典。当输入为两个值时(比如[1,2]),第一组键值对无法添加到用于后续步骤的第二个反转字典small中。

原代码

from typing import List

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        dictionary = {} 
        small = {} 
        answer = []
        i = 0
        if len(nums) <= 1:
            return nums
        for number in nums:
            dictionary[number]= 1 + dictionary.get(number,0)
        for key , v in dictionary.items():
            print(key,v)
            # 这里能正确打印所有键值对
            small[v] = key 
            # 但输入是两个值时,比如[1,2],dictionary是{1:1,2:1},第一个键值对不会被加入small,只有第二个会,这是问题所在
        print(small)
        while i < k:
            count = max(small)
            answer.append(small[count])
            del small[count]
            i +=1 
        return answer
问题原因

核心问题是字典键的唯一性。当输入[1,2]时,两个数字的频率都是1,执行small[v] = key时,第一个操作会把small[1]设为1,但第二个操作会用2覆盖掉这个值,最终small里只剩{1:2}——不是第一个键值对没加进去,是被后面的覆盖了。

解决方案

不能直接用频率当small的键,得让相同频率的元素存到同一个列表里。修改后的代码如下:

from typing import List

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        freq_dict = {} 
        freq_groups = {} 
        result = []
        count = 0
        
        if len(nums) <= 1:
            return nums
        
        # 统计每个数字的出现频率
        for num in nums:
            freq_dict[num] = freq_dict.get(num, 0) + 1
        
        # 按频率分组,相同频率的数字放到列表中
        for num, freq in freq_dict.items():
            if freq not in freq_groups:
                freq_groups[freq] = []
            freq_groups[freq].append(num)
        
        # 按频率从高到低排序,依次取元素直到够k个
        sorted_freqs = sorted(freq_groups.keys(), reverse=True)
        for freq in sorted_freqs:
            for num in freq_groups[freq]:
                if count < k:
                    result.append(num)
                    count += 1
                else:
                    break
            if count >= k:
                break
        
        return result
说明
  1. 把small改成freq_groups,键是频率,值是对应频率的数字列表,避免相同频率的元素被覆盖。
  2. 对频率进行降序排序,从高到低遍历,逐个取出元素直到收集够k个。
  3. 测试[1,2]时,freq_groups会是{1: [1,2]},取top2就能返回两个元素,符合预期。

内容的提问来源于stack exchange,提问作者baconandeggs47

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 02:16:23