在 Python 中哈希 Maps/Dictionaries

Hash Maps/Dictionaries in Python

遇到这个 leet 代码。

prevMap = {} #Value:Index
    for i,n in enmuerate(nums):
        diff = target - n
        if diff in prevMap:
            return (prevMap[diff],i)
        prevMap[n] = i                  

这是著名的使用散列映射的二和问题的摘录。

我是 Python 的散列图的新手,因此没有意识到您可以使用 'in' 函数直接从 dictionary/hashmap 中查找值。但是,我不明白的是最后两行。 倒数第二行试图 return 哈希图中值的索引。据我以往所知,hashMap[index] = value 不应该是相反的吗? hashMap[value] = index?

是否也有相反的作用

至于最后一行,我们试图将列表 nums 放入哈希图中。在这种情况下,它不应该是 prevMap[i] = n,因为我们试图将值 n 映射到 hashmap 的索引 i 中吗?

谢谢。

hashMap[索引] = 值? hashMap[value] = index?

是否也有相反的作用

至于最后一行,我们正在尝试将列表 nums 放入 hashmap 中。在这种情况下,它不应该是 prevMap[i] = n,因为我们试图将值 n 映射到 hashmap 的索引 i 中吗?

谢谢。

你把事情搞混了。在倒数第二行中,您返回 tuple of the index within the list stored in the dictionary 作为两个总和的一部分的值之一,而 i 又是列表中的 索引 - 而不是字典 为两个总和的第二个总和。 在最后一行中,您将索引存储在列表中以获取特定值。

我相信您混淆了列表/字典的工作方式。您不能按索引访问字典。仅仅因为语法与 [] 相同并不意味着访问值的方式相同。

l = ["val1", "val2", "val3", "val4"]
d = {
    "key1": "val1",
    "key2": "val2"
}

d_with_keys_defined_as_index = {
    0: "val1",
    1: "val2"
}

# Access first element of list
print(l[0])
# KeyError, a dictionary cannot be accessed by index (except index is explicitly defined as a key)
print(d[0])
# access value by key
print(d["key1"])
# now 0 is explicitly defined as a key, so we can access it using that key. This is still not an access by index though
print(d_with_keys_defined_as_index[0])