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()。