题解 | #两数之和#
两数之和
https://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f
from typing import List class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: ## 哈希表,用字典实现(python的字典即用哈希表实现) tab_hash = {} res = [] for ind, val in enumerate(numbers): # 计算差值 val2 = target - val # 在哈希表(即字典中)中查找差值 ind2 = tab_hash.get(val2) # 判断所需差值是否存在 # 迷惑点:遍历到第一个数,一定不存在。所以添加到列表,遍历到差值的时候,去找第一个数。好处,排除差值和第一个数相同,且列表中只出现一次的情况 if ind2 is not None: # 存在,返回结果 res = [ind + 1, ind2 + 1] res.sort() break else: # 不存在,保存当前结果到哈希表中 tab_hash[val] = ind return res