两数之和
python 解法
牺牲空间提升速度
- 两数的和已经告知,便利待搜索列表的时候,可以寻找其余数是否也在列表之中;
- 创建一个hash表,使这个表能够保存两层信息,一个是余数信息,一个是余数的索引号,利用hash表将其保存下来
- 如果后续的遍历之中,出现了已经保存的余数信息,那么就是答案了
def twoSum(self, nums: list[int], target: int) -> list[int]:
hash = {}
for idx,item in enumerate(nums):
remainder = target - item
if item in hash:
return [idx,hash[item]]
hash[remainder] = idx