Leetcode 1.两数之和 Two Sum - Python 哈希法

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        pool = dict()
        for idx, num in enumerate(nums):
            if target - num not in pool:
                pool[num] = idx
            else:
                return [idx,pool[target - num]]

此题的情况:需要返回某一值对应的下标,所以不能用set,因为其没有下标。

而数组哈希表也不适用,因为此题所喂的数据(数组元素)有重复元素,且大小不定。若用数组可能会出现哈希碰撞和空间大量浪费的情况。

综上,这时我们就要考虑用Map了,即key:value映射关系。在Python中即为Dictionary字典,初始化函数dict()。


版权声明:本文为rendalian原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。