两数、三数之和

【给出一个整型数组 numbers 和一个目标值 target,请在数组中找出两个加起来等于目标值的数的下标,返回的下标按升序排列。】

class Solution:
    def twoSum(self , numbers: List[int], target: int) -> List[int]:
        # write code here
        hashmap = {}
        for index, num in enumerate(numbers):
            another_num = target - num
            if another_num in hashmap:
                return [hashmap[another_num]+1, index+1]
            hashmap[num] = index
        return None

【给出一个有n个元素的数组S,S中是否有元素a,b,c满足a+b+c=0?找出数组S中所有满足条件的三元组。】

class Solution:
    def threeSum(self , num: List[int]) -> List[List[int]]:
        # write code here
        num.sort()
        res = []
        
        for k in range(len(num)-2):
            
            if num[k] > 0:break
            if k > 0 and num[k] == num[k - 1]: continue
            i,j = k+1,len(num)-1
            while i<j:
                s = num[i] + num[j] + num[k]
                if s<0:
                    i += 1
                    while i<j and num[i]==num[i-1]:i+=1
                elif s>0:
                    j -= 1
                    while i<j and num[j]==num[j+1]:j-=1
                else:
                    res.append([num[k],num[i],num[j]])
                    
                    i += 1
                    j -= 1
                    while i<j and num[i]==num[i-1]:i+=1
                    while i<j and num[j]==num[j+1]:j-=1
                    
        return res
                    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值