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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路:
方法一:暴力搜索,最简单也是最容易想到的方法,两层嵌套遍历数组,计算和,时间复杂度为
方法二:两次遍历,一次遍历将数组下标和对应值放入hash表中,第二次遍历计算 target - num[i] 的值,在hash表中查找是否存在该结果,时间复杂度
,空间复杂度
方法三:一次遍历,一边访问数组,计算与target的差值,如果结果不存在hash表中,就把当前数组值和下标加入hash表,如果存在直接返回结果。时间复杂度
,空间复杂度
后两种方法实现如下:
class Solution(object):
def twoSum2(self, nums, target):
value_index = dict()
for i in range(len(nums)):
value_index[nums[i]] = i
for i in range(len(nums)):
diff = target - nums[i]
if diff in value_index:
return [i, value_index.get(diff)]
return []
def twoSum3(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
value_index = dict()
for i in range(len(nums)):
diff = target - nums[i]
if diff in value_index:
return [value_index.get(diff), i]
value_index[nums[i]] = i
return []