2sum
-
题目描述
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. -
示例
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]. -
分析
思路不是很难,因为假设只有一种解决方法,所以直接采用固定一个数,寻找另一个数是否在数组中即可,这样的复杂度为O(n2),需要寻找一个O(n)复杂度的解法,可以建立一个字典,将遍历过的数和索引放在字典中,空间换时间。
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
for i in range(len(nums)):
other = target-nums[i]