题目
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.
解题思路
边遍历数组,边将数字及出现的位置存在字典里,当target减去当前的数,出现在字典中,返回结果
代码
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i, n in enumerate(nums):
if target - n in dic:
return [dic[target - n], i]
dic[n] = i