Description
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Solution
因为每个数字只出现1次,所以可以用字典实现一个数字到下标的映射,然后就循环一遍找与每个数字加起来能得到target的数是否存在,存在就返回答案,复杂度O(n)
Code
class Solution():
def twoSum(self, nums, target):
nums2={
}
n=len(nums)
res=[]
for i in range(0,n):
nums2[nums[i]]=i
for i in range(0,n):
if nums2.get(target-nums[i],i)>i:
res.append(i)
res.append(nums2.get(target-nums[i]))
return res