0001 - Two Sum
Python Leetcode 问题: 0001 - Two Sum
题目
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
传入 数字列表
及 最后答案加总数值
,回传 最后答案加总数值
是 数字列表
的第几个跟第几个数字的加总
答案
from typing import List
class Solution:
def twoSum(self, nums_list: List[int], final_sum_value: int) -> List[int]:
# 数字反向对应表
num_reverse_mapping = {}
# 列举数字清单
enumerate_nums_list = enumerate(nums_list)
for current_num_key, current_num_value in enumerate_nums_list:
# 其他键值数值
other_value = final_sum_value - current_num_value
# 数值是否存在反转对应表
is_other_value_exist = (other_value in num_reverse_mapping)
if is_other_value_exist:
# 若其他数值有存在反转表,回传 key 值
other_num_key = num_reverse_mapping[other_value]
return [other_num_key, current_num_key]
# 没有找到数值,将数值位置 key 记录下来
num_reverse_mapping[current_num_value] = current_num_key
if __name__ == '__main__':
# begin
s = Solution()
print(s.twoSum([3, 2, 4], 6))
print(s.twoSum([3, 2, 4], 7))