hash_table 初始化,发生了什么?

问题描述

我有一个关于以下有关哈希表的代码快速问题。对于第 5 行-发生了什么?所以我们将 'hash_table' 初始化为一个字典。然后对于 nums 中的每个元素 'i' 我们做 hash_table[i]??但是 hash_table 是空的——因为刚刚初始化它?这是我感到困惑的地方。 说我们通过执行 hash_table['i'] 来定义键是否正确?如果是这种情况,为什么 +=1? (P.S. nums 是一个整数列表)

class Solution:
    def singleNumber(self,nums: List[int]) -> int:
        hash_table = defaultdict(int)
        for i in nums:
            hash_table[i] += 1

        for i in hash_table:
            if hash_table[i] == 1:
               return i

解决方法

我认为您对 defaultdict 的理解是正确的:如果密钥不存在,那么密钥将被添加一个默认值。在 defaultdict(int) 的情况下,默认值为 0。但是您传递的 nums 是什么?如果 nums 不为空,则在第一个 hash_table 循环后 for 不会为空。然而,方法 singleNumber 只返回一个值,它将是 hash_table 的第一个键,只出现在 nums 列表中一次。正如 Tomericlo 所指出的,您的 hash_table 更像是一组计数器,用于计算 nums 中每个不同整数出现的次数。我已修改您的代码以插入 print 语句(并缺少 import 语句)并添加了一个测试用例。

请注意,如果 nums 中没有整数只出现一次,那么您的代码永远找不到匹配项,也永远不会发出 return 语句,这相当于返回值 None

from collections import defaultdict
from typing import List


class Solution:
    def singleNumber(self,nums: List[int]) -> int:
        hash_table = defaultdict(int)
        for i in nums:
            hash_table[i] += 1

        print(hash_table) # added statement

        for i in hash_table:
            if hash_table[i] == 1:
               return i

# test case:  
solution = Solution()
print(solution.singleNumber([7,6,7,12]))

打印:

defaultdict(<class 'int'>,{7: 2,6: 1,12: 1})
6