- 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的 两个 整数。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
- 示例: 给定 nums = [2, 7, 11, 15],
target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
方法一:
暴力解法, 时间复杂度O(n^2)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
index_list = []
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
index_list.append(i)
index_list.append(j)
print(list(set(index_list)))
return index_list
方法二:
使用哈希表,通过以空间换取速度的方式,我们可以将查找时间从 O(n^2)降低到 O(n)。在python中列表字典的即为哈希类型。**
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashtable = {}
for i, num in enumerate(nums):
if target - num in hashtable:
return [hashtable[target - num], i]
hashtable[num] = i
return []
方法二比方法一快了十多倍,原因在于方法二使用了空间换时间的思路,可以将查找时间从 O(n^2)降低到 O(n)。在python中列表字典的即为哈希类型。
另一种写法:
利用哈希字典查找,通过枚举将数值对应关系放入字典中,然后判断目标值和每一个值得差值在不在字典中。时间复杂度为O(n) 空间复杂度为O(n),相对容易理解一些
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
index_list = []
for i, m in enumerate(nums):
dict[m] = i
for i, m in enumerate(nums):
j = dict.get(target - m)
if j is not None:
index_list.append(i)
index_list.append(j)
return list(set(index_list))
方法三:
遍历列表,计算目标数与nums[i]的差,判断差是否在列表nums[i+1]里面即可,此法更加简单易懂
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
res = []
# 遍历列表
for i in range(len(nums)):
# 计算需要找到的下一个目标数字
ans = target-nums[i]
# 在剩下的元素,查找是否存在该数字
if ans in nums[i+1:]:
# 若存在,返回答案。这里由于是两数之和,可采用.index()方法
# 获得目标元素在nums[i+1:]这个子数组中的索引后,还需加上i+1才是该元素在nums中的索引
res = [i, nums[i+1:].index(ans)+i+1]
return res
return res