题解 | #两数之和#
两数之和
https://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param numbers int整型一维数组 # @param target int整型 # @return int整型一维数组 # class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: # write code here # 用字典做哈希表 hash = {} result = [] for i, n in enumerate(numbers): if target - n in hash: # 找到了,而且原来在里边的下标一定更小,直接放到数组里 result.append(hash[target - n]) result.append(i + 1) break if n not in hash: # 下标是0开始,所以加1 hash[n] = i + 1 return result