【Leetcode】15. 三数之和

一、题目

 难度不小

 注意是不能重复

 Python提交格式,返回一个list

 二、暴力解法

排序 + 三重循环

有没有像我这样的傻子,三重循环,还没去重

后来发现要去重,必须要先排序,然后判断一下当前的数是否跟前面那个数相同,相同的话就跳过,实现去重。

 三重循环:

  二、暴力解法(优化)

排序 + 两重循环 + HashMap

前面解法用了三重循环,我们优化的方向就是如何减少一层循环,比如减少第三层循环。

可以用HashMap来替代第三重循环,因为第三重for循环是用来查找第三个数的,HashMap一样可以用来查找,而且for循环的查找效率是O(n)HashMap的查找效率是O(1),只不过我们需要付出空间作为代价,以空间换时间。

HashMap来替代最后一层for循环就是一个很常见的套路。

这个题难点在于如何去除重复解,思想是利用排序避免重复答案,只要确定了第一个元素,就能降低时间复杂度,变成Leetcode中的第一题(twoSum),再利用双指针(类似折半查找里面的头指针和尾指针)去找到所有解。

三、优化算法

排序 + 双指针

首先看下面的两个图解(摘自Leetcode): 

然后再看看算法流程:

 

四、代码

1. 暴力解决(排序 + 三重循环

"""
Time:2022/11/24 10:09
Author:ECCUSYB
"""


class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        n = len(nums)
        if not nums or n < 3:
            return []
        threelist = []
        for i in range(n):
            if i > 0 and nums[i - 1] == nums[i]: continue
            for j in range(i, n):
                if j > (i+1) and nums[j - 1] == nums[j]: continue
                for k in range(j, n):
                    if k > (j + 1) and nums[k - 1] == nums[k]: continue
                    if i != j and i != k and j != k and nums[i] + nums[j] + nums[k] == 0:
                        threelist.append([nums[i], nums[j], nums[k]])
        return threelist


test = Solution()
nums = [-1, 0, 1, 2, -1, -4]
re = test.threeSum(nums)

print(re)

2. 暴力解决(排序 + 两重循环 + HashMap

"""
Time:2022/11/24 10:31
Author:ECCUSYB
"""


class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        map = {}

        n = len(nums)
        if not nums or n < 3:
            return []

        for i in range(len(nums)):
            map[nums[i]] = i
        threelist = []
        # print(map) {-4: 0, -1: 2, 0: 3, 1: 4, 2: 5}
        for i in range(0, len(nums) - 2):
            x = nums[i]
            if x > 0: break
            if i > 0 and nums[i - 1] == nums[i]: continue
            for j in range(i + 1, len(nums) - 1):
                y = nums[j]
                if x + y > 0: break
                if j > i + 1 and nums[j - 1] == nums[j]: continue
                z = 0 - x - y
                if z in map.keys() and map.get(z) > j:
                    threelist.append([x, y, z])
        return threelist


test = Solution()
nums = [-1, 0, 1, 2, -1, -4]
re = test.threeSum(nums)

print(re)

3. 优化(排序 + 双指针

"""
Time:2022/11/23 22:51
Author:ECCUSYB
"""


class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        n = len(nums)
        if not nums or n < 3:
            return []
        nums.sort()
        res = []
        for i in range(n):
            # 如果第一个值大于零,直接返回空
            if nums[i] > 0:
                return res
            # 如果当前值等于上一个值,跳过,进入下一次循环,去除重复值
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            L = i + 1
            R = n - 1
            while (L < R): # 如果 L>R 或者 L=R 就结束
                if nums[i] + nums[L] + nums[R] == 0:
                    res.append([nums[i], nums[L], nums[R]])
                    while L < R and nums[L] == nums[L + 1]:
                        L = L + 1
                    while L < R and nums[R] == nums[R - 1]:
                        R = R - 1
                    L = L + 1
                    R = R - 1
                # 如果三数之和大于零,就将R--
                elif nums[i] + nums[L] + nums[R] > 0:
                    R = R - 1
                else:
                    L = L + 1
        return res


test = Solution()
nums = [-1, 0, 1, 2, -1, -4]
re = test.threeSum(nums)

print(re)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不菜不菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值