Python - LeetCode - 两数之和
2018-12-23 本文已影响0人
拔萝卜占坑
描述:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的
数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
def twoSumOne(nums,target):
l = len(nums)
for num in range(l):
one = nums[num]
for num1 in range(l):
if(num == num1):
continue
two = nums[num1]
if((one + two) == target):
return [num,num1]
def twoSumTwo(nums,target):
l = len(nums)
for i in range(l):
one = nums[i]
two = target - one
if(two not in nums):
continue
j = nums.index(two)
if(j == i):
continue
if(j != None):
return [i,j]
def twoSumThree(nums,target):
l = len(nums)
dictOne = {nums[i]:i for i in range (l)}
dictTwo = {i:target - nums[i] for i in range(l)}
for j in range(l):
index = dictOne.get(dictTwo.get(j))
if(index != None):
return [j,index]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="two num add")
parser.add_argument('-l',dest='list',metavar='N',type=int,nargs='+',help='intergers for two add')
args = parser.parse_args()
print(args.list)
print(twoSumTwo(args.list,10))