python-3.x 前K个频繁元素Leetcode 347

cclgggtu  于 2023-11-20  发布在  Python
关注(0)|答案(1)|浏览(101)

对于我的代码,只要只有两个值,它就不能处理两个值的输入。任何大于两个值的值都没有问题,并正确地创建字典。对于两个值,第一组键值对不会添加到第二个字典中,以便在下游步骤中翻转。

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)
            // the key value pairs are correctly printed here 
            small[v] = key 
            // yet here if there are only two values in the input (i.e. [1,2])   
             the first set of key value pairs in DICTIONARY {1:1 , 2:1}  won't get added to SMALL yet the                                        
             second pair will, this is where I'm lost
        print(small)
        while i < k:
            count = max(small)
            answer.append(small[count])
            del small[count]
            i +=1 
        return answer

字符串

sxpgvts3

sxpgvts31#

这个问题并不特别是关于两个值。当每个值只有一个时,例如,如果你的输入是[1,2,3,4,5],它会有类似的问题small
这是因为small[v] = key就像small[1] = 1后面跟着small[1] = 2。所以每当你有另一个只出现一次的key时,small[1]的值就会被替换。

相关问题