7.查找两个总和为特定值的索引
题目描述
给定一个数组,找到两个总和为特定值的索引。
例如给定数组 [1, 2, 3, -2, 5, 7],给定总和 7,则返回索引 [1, 4]。
思路一
O(n²)暴力
代码
class Solution(object):
def two_sum(self, nums, val):
if nums is None or val is None:
raise TypeError('nums or target cannot be None')
if not nums:
raise ValueError('nums cannot be empty')
lenth = len(nums)
res = []
for i in range(lenth):
temp = val - nums[i]
for j in range(lenth):
if nums[j] == temp:
res.append(i)
res.append(j)
return res
return None
思路二
使用list内置函数 O(n²)
代码
class Solution(object):
def two_sum(self, nums, val):
if nums is None or val is None:
raise TypeError('nums or target cannot be None')
if not nums:
raise ValueError('nums cannot be empty')
lenth = len(nums)
res = []
for i in range(lenth):
temp = val - nums[i]
if temp in nums:
res.append(i)
res.append(nums.index(temp))
return res
return None
思路三
哈希表
代码
class Solution(object):
def two_sum(self, nums, val):
if nums is None or val is None:
raise TypeError('nums or target cannot be None')
if not nums:
raise ValueError('nums cannot be empty')
cache = {}
for index, num in enumerate(nums):
cache_val = val - num
if num in cache:
return [cache[num], index]
else:
cache[cache_val] = index
return None