给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
def twoSum(nums, target):
lens = len(nums)
j=-1
for i in range(lens):
if (target - nums[i]) in nums:
if (nums.count(target - nums[i]) == 1)&(target - nums[i] == nums[i]):#如果num2=num1,且nums中只出现了一次,说明找到是num1本身。
continue
else:
j = nums.index(target - nums[i],i+1) #index(x,i+1)是从num1的位置后,寻找x,最终返回x位置。
break # 打破了最小封闭for或while循环
if j>0:
return [i,j]
else:
return []
nums = [2, 7, 11, 15]
target = 13
print(twoSum(nums, target))
原文:https://www.cnblogs.com/ygao/p/14022508.html