「LEETCODE-15」三数之和

题目简介:
在这里插入图片描述
解题思路:
a+b+c=0,无非有一下几种情况:
1⃣️a,b,c三个数字有两个是相同的,相同的数字在数组中出现的次数必须大于1;
2⃣️a为负数,b为正数数,c小于a或者c大于b;
3⃣️c=0.(除此之外,之所以不考虑:负数<c<正数是因为恰恰这么做可以去除“重复的三元组”,比如[-3,-2,5],[-2,-3,5])

代码:

def threeSum(self, nums: List[int]) -> List[List[int]]:
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        dict = {}
        pos=[]
        neg=[]
        for ele in nums:
            if ele not in dict:
                dict[ele] = 0
            dict[ele] += 1
            
        if 0 in dict and dict[0] > 2:
            result = [[0,0,0]]
        else:
            result = []
            
        for ele in dict:
            if ele>0:
                pos.append(ele)
            elif ele<0:
                neg.append(ele)
        
        for p in pos:
            for n in neg:
                target = -(p + n)
                if target in dict:
                    #两个相同的整数或者负数
                    if target in [p,n] and dict[target]>1:
                        result.append([p,n,target])
                    elif target < n or target > p or target == 0:
                        result.append([n, target, p])
                        
        return result
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值