【leedcode】0001. 两数之和

x33g5p2x  于2021-11-09 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(106)


 

【leedcode】0001.两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

方法一: 

def twoSum(nums,target):
	for i,n in enumerate(nums):
		for j in range(i+1,len(nums)):
			if n+nums[j]==target:
				return [i,j]
	else:
		return []

'''	
>>> twoSum([2,7,11,15],9)
[0, 1]
>>> twoSum([0,2,7,11,15],9)
[1, 2]
>>> twoSum([0,2,7,11,15],17)
[1, 4]
>>> twoSum([0,2,7,11,15],5)
[]
>>> 
'''

方法二:

def twoSum(nums, target):
	for i,n in enumerate(nums):
		m = target - n
		t = nums[i+1:]
		if m in t:
			return [i,i+1+t.index(m)]
	else:
		return []

'''
>>> twoSum([2,7,11,15],9)
[0, 1]
>>> twoSum([0,2,7,11,15],9)
[1, 2]
>>> twoSum([0,2,7,11,15],17)
[1, 4]
>>> twoSum([0,2,7,11,15],5)
[]
>>> 
'''

方法三:

def twoSum(nums, target):
        t = {}
        for i,n in enumerate(nums):
            if target-n in t:
                return [t[target-n], i]
            else:
                t[n] = i
        else:
                return []

'''
>>> twoSum([2,7,11,15],9)
[0, 1]
>>> twoSum([0,2,7,11,15],9)
[1, 2]
>>> twoSum([0,2,7,11,15],17)
[1, 4]
>>> twoSum([0,2,7,11,15],5)
[]
>>> 
'''

方法四:

>>> from itertools import combinations as comb
>>> twoSum = lambda nums,target:[[nums.index(i[0]),nums.index(i[1])] for i in comb(nums,2) if sum(i)==target][0]
>>> twoSum([2,7,11,15],9)
[[0, 1]]
>>> twoSum([0,2,7,11,15],9)
[[1, 2]]
>>> twoSum([0,2,7,11,15],17)
[[1, 4]]
>>> twoSum([0,2,7,11,15],5)
[]
>>> twoSum([2,3,6,7,11,15],9)
[[0, 3], [1, 2]]
>>>

欢迎加入“派森特给站”社区!

https://bbs.csdn.net/forums/PythonTogether

相关文章

微信公众号

最新文章

更多