给出一个整型数组 numbers 和一个目标值 target,请在数组中找出两个加起来等于目标值的数的下标,返回的下标按升序排列。
(注:返回的数组下标从1开始算起,保证target一定可以由数组里面2个数字相加得到)
数据范围:
,
,
要求:空间复杂度
,时间复杂度
[3,2,4],6
[2,3]
因为 2+4=6 ,而 2的下标为2 , 4的下标为3 ,又因为 下标2 < 下标3 ,所以返回[2,3]
[20,70,110,150],90
[1,2]
20+70=90
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param numbers int整型一维数组
# @param target int整型
# @return int整型一维数组
#
class Solution:
def twoSum(self , numbers: List[int], target: int) -> List[int]:
d = {}
for i in range(len(numbers)):
m = numbers[i]
if target - m in d:
return (d[target - m] + 1, i + 1)
d[m] = i
#Python3
class Solution:
def twoSum(self , numbers: List[int], target: int) -> List[int]:
# write code here
dd = {}
ll = len(numbers)
for i in range(ll):
if target - numbers[i] in dd:
return [dd[target - numbers[i]]+1, i+1]
dd[numbers[i]] = i
#总用时161ms # 用例全部通过版本: class Solution: def twoSum(self , numbers: List[int], target: int) -> List[int]: # write code here for i in range(len(numbers) - 1): if numbers[i] <= target: # 用于降低时间复杂度 for j in range(i+1, len(numbers)): if numbers[i] + numbers[j] == target: return [i+1, j+1] return []
class Solution:
def twoSum(self , numbers: List[int], target: int) -> List[int]:
tmp_dict={}
for i in range(len(numbers)):
if target - numbers[i] in tmp_dict.keys():
return [tmp_dict[target - numbers[i]]+1,i+1]
tmp_dict[numbers[i]]=i # 方法一:哈希表
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
## 哈希表,用字典实现(python的字典即用哈希表实现)
tab_hash = {}
res = []
for ind, val in enumerate(numbers):
# 计算差值
val2 = target - val
# 在哈希表(即字典中)中查找差值
ind2 = tab_hash.get(val2)
# 判断所需差值是否存在
if ind2 is not None: # 存在,返回结果
res = [ind + 1, ind2 + 1]
res.sort()
break
else: # 不存在,保存当前结果到哈希表中
tab_hash[val] = ind
return res
# 方法二: 双指针
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
# 写入索引
data = [(val, ind) for ind, val in enumerate(numbers)]
# 排序
data.sort(key=lambda x: x[0])
# 由于有序, 用双指针从前后同时查找
ind1, ind2 = 0, len(data) - 1
while True:
# 终止条件(题目可知,一定可以找到)
if data[ind1][0] + data[ind2][0] == target:
break
# 当前值较小,增大左边的索引
if data[ind1][0] + data[ind2][0] < target:
ind1 += 1
# 当前值较大,减小右边的索引
if data[ind1][0] + data[ind2][0] > target:
ind2 -= 1
res = [data[ind1][1] + 1, data[ind2][1] + 1] # 题目中要求的数组下标从1开始算起
res.sort() # 保证从小到大
return res
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: # 创建哈希表,用于保存值、下标键值对 hash = dict() # 在哈希表中查找target-numbers[i] for i in range(len(numbers)): temp = target - numbers[i] if temp not in hash: hash[numbers[i]] = i else: return [hash[temp]+1,i+1]
def twoSum(self , numbers: List[int], target: int) -> List[int]: # write code here k=[] for j in range(len(numbers)): for i in range(len(numbers)-1): a=numbers[len(numbers)-1-j]+numbers[len(numbers)-1-j-i-1] k.append(a) if target in k: b=len(numbers)-1-j+1 c=len(numbers)-1-j-i d=[c,b] return d