大家好,又见面了,我是你们的朋友全栈君。
给定列表a和一个目标值target,求列表中两数之和为target的值的索引;
a = [1,5,6,8,9,4,5,6,3,2,1,7,5,6,9,8,4,5,6,2,1,0,1,2,0,1,2,5,9,10]
b = [11,55,88,99,66,4,77,33,22,1,6,12,35]
穷举(适应性强)
def x(nums,target):
result = []
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j] == target:
result.append((i+1,j+1))
return result
#print(x(b,10))
双指针(仅限于非重复有序列表的查询)
def y(nums,target):
result = []
start = 0
end = len(nums)-1
while start < end:
if nums[start] + nums[end] == target:
result.append((start+1,end+1))
end -= 1
start += 1
elif nums[start] + nums[end] > target:
end -= 1
elif nums[start] + nums[end] < target:
start += 1
return result
# print(y(sorted(b),10))
哈希字典查找(仅限于非重复列表的查询)
def z(nums,target):
result = []
dict_y = {}
for i in range(len(nums)):
m = nums[i]
if target-m in dict_y:
result.append((dict_y[target-m]+1,i+1))
dict_y[m] = i
return result
#print(z(b,10))
使用字典进行存储(仅限于非重复列表的查询)
def h(nums,target):
result = []
xxx = []
for i in range(len(nums)):
if target-nums[i] in result:
xxx.append([result.index(target-nums[i])+1,i+1])
else:
result.append(nums[i])
return xxx
print(h(b,10))
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/135578.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...