2sum,3sum
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
myhash={}
length=len(nums)
for i in range(length):
n=nums[i]
if n in myhash: #搜索的复杂度是o(1)
return [myhash[n],i]
else:
myhash[target-n]=i
如果要输出所有的标号,可以用桶散列,拉链法进行处理
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort() #运算复杂度小于整体的运算复杂度,且能帮助主要部分减少运算复杂度
def twoSum(self, nums: List[int], target: int) -> List[List[int]]: #转化成单数和2sum来解决
myhash = {}
length = len(nums)
ans = list()
for i in range(length):
n = nums[i]
if n in myhash:
ans.append([myhash[n],i])
if target - n not in myhash:
myhash[target - n] = i
return ans
z=list()
for i in range(len(nums) - 2):
if nums[i]>0: break #三正数相加肯定为正
if i==0 or nums[i-1] !=nums[i]:
n = nums[i]
nums_use = nums[i + 1:]
target = 0 - n
xu_use = twoSum(self, nums_use, target) #得到的是后个元素相对于第一个元素的坐标
xu_use.reverse()
for a in xu_use:
a_aff=[a[0]+i+1 , a[1]+i+1]
z_aff = [i] + a_aff
ans_aff=[nums[z_aff[0]],nums[z_aff[1]],nums[z_aff[2]]] #处理连续为0的特殊情况,不要重复输出容易漏掉
if len(z) == 0 or ans_aff != z[-1]:
z.append(ans_aff)
return z