hash_table 初始化,发生了什么?

hash_table initialisation, what is happening?

我有一个关于哈希表的以下代码的快速问题。对于第 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的理解是正确的:如果key不存在,那么key会被添加一个默认值。在 defaultdict(int) 的情况下,默认值将为 0。但是您传递的 nums 是什么?如果 nums 不为空,则 hash_table 在第一个 for 循环后不会为空。但是,方法 singleNumber 只是 returns 一个值,这将是 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