「LEETCODE-15」三数之和

题目简介:
「LEETCODE-15」三数之和_第1张图片
解题思路:
a+b+c=0,无非有一下几种情况:
1⃣️a,b,c三个数字有两个是相同的,相同的数字在数组中出现的次数必须大于1;
2⃣️a为负数,b为正数数,c小于a或者c大于b;
3⃣️c=0.(除此之外,之所以不考虑:负数)

代码:

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

你可能感兴趣的:(算法)