我是靠谱客的博主 酷酷砖头,这篇文章主要介绍Leetcode——两数之和(twoSum)、三数之和(threeSum)——Python,现在分享给大家,希望可以做个参考。

一、两数之和

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
#对应每个测试案例,输出两个数,小的先输出。
# ls = []
# if not isinstance(nums, list):
#
return ls
# for i, v in enumerate(nums):
#
for v1 in nums[i:]:
#
if (v + v1) == target:
#
ls.append([v,v1])
# if ls:
#
return ls[0]
# else:
#
return ls
keys={}
for i in xrange(len(nums)):
if target-nums[i] in keys:
return [keys[target-nums[i]],i]
if nums[i] not in keys:
keys[nums[i]]=i

二、三数之和

class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
res =[]
lennums= len(nums)
for i in range(lennums):
left =i+1
right =lennums-1
if i>0 and nums[i-1]==nums[i]:
left+=1
continue
while left<right:
sumthree = nums[i]+nums[left]+nums[right]
if sumthree==0:
res_col = [nums[i],nums[left],nums[right]]
res.append(res_col)
left+=1
right-=1
while nums[left]==nums[left-1] and left<right:
left+=1
while nums[right]==nums[right+1] and left<right:
right-=1
if sumthree<0:
left+=1
if sumthree>0:
right-=1
return res

 

最后

以上就是酷酷砖头最近收集整理的关于Leetcode——两数之和(twoSum)、三数之和(threeSum)——Python的全部内容,更多相关Leetcode——两数之和(twoSum)、三数之和(threeSum)——Python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(124)

评论列表共有 0 条评论

立即
投稿
返回
顶部