每日一练

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:

给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort() #排序没啥用,整理起来思路清晰一点,嗯
        a = []
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                l = nums.copy()
                l.remove(l[i])
                l.remove(l[j-1])
                if -(nums[i]+nums[j]) in l:
                    m = sorted([nums[i],nums[j],-(nums[i]+nums[j])])
                    if m not in a:
                        a.append(m) 
        return a

以上为自己编写运行超时的代码,测试集到315/318了,逻辑方面应该没什么太大问题。
然后看了别的大佬的哈希算法,代码如下

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        negative = dict()
        positive = dict()
        zero = 0
        for num in nums:
            if num > 0:
                if num in positive.keys():
                    positive[num] += 1
                else:
                    positive[num] = 1
            elif num < 0:
                if num in negative.keys():
                    negative[num] += 1
                else:
                    negative[num] = 1
            else:
                zero += 1
        result = []
        if zero >= 3:
            result.append([0, 0, 0])
        if zero > 0:
            for num in negative.keys():
                if (-num) in positive.keys():
                    result.append([num, 0, -num])
        for num in negative.keys():
            if negative[num] >= 2 and (-num) * 2 in positive.keys():
                result.append([num, num, - num * 2])
        for num in positive.keys():
            if positive[num] >= 2 and (-num) * 2 in negative.keys():
                result.append([-num * 2, num, num])
        keysOfNegative = list(negative.keys())
        for num1Index in range(len(keysOfNegative) - 1):
            num1 = keysOfNegative[num1Index]
            for num2 in keysOfNegative[num1Index + 1:]:
                if -(num1 + num2) in positive.keys():
                    result.append([num1, num2, -(num1 + num2)])
        keysOfPositive  = list(positive.keys())
        for num1Index in range(len(keysOfPositive) - 1):
            num1 = keysOfPositive[num1Index]
            for num2 in keysOfPositive[num1Index + 1:]:
                if -(num1 + num2) in negative.keys():
                    result.append([-(num1 + num2), num1, num2])
        return result

时间复杂度巨低,把三正三复的情况排除了,总体感觉就是把一个大的二重遍历变为好多小的二重遍历。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值