• 【Leetcode】15. 三数之和


    一、题目

     难度不小

     注意是不能重复

     Python提交格式,返回一个list

     二、暴力解法

    排序 + 三重循环

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

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

     三重循环:

      二、暴力解法(优化)

    排序 + 两重循环 + HashMap

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

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

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

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

    三、优化算法

    排序 + 双指针

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

    然后再看看算法流程:

     

    四、代码

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

    1. """
    2. Time:2022/11/24 10:09
    3. Author:ECCUSYB
    4. """
    5. class Solution(object):
    6. def threeSum(self, nums):
    7. """
    8. :type nums: List[int]
    9. :rtype: List[List[int]]
    10. """
    11. nums.sort()
    12. n = len(nums)
    13. if not nums or n < 3:
    14. return []
    15. threelist = []
    16. for i in range(n):
    17. if i > 0 and nums[i - 1] == nums[i]: continue
    18. for j in range(i, n):
    19. if j > (i+1) and nums[j - 1] == nums[j]: continue
    20. for k in range(j, n):
    21. if k > (j + 1) and nums[k - 1] == nums[k]: continue
    22. if i != j and i != k and j != k and nums[i] + nums[j] + nums[k] == 0:
    23. threelist.append([nums[i], nums[j], nums[k]])
    24. return threelist
    25. test = Solution()
    26. nums = [-1, 0, 1, 2, -1, -4]
    27. re = test.threeSum(nums)
    28. print(re)

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

    1. """
    2. Time:2022/11/24 10:31
    3. Author:ECCUSYB
    4. """
    5. class Solution(object):
    6. def threeSum(self, nums):
    7. """
    8. :type nums: List[int]
    9. :rtype: List[List[int]]
    10. """
    11. nums.sort()
    12. map = {}
    13. n = len(nums)
    14. if not nums or n < 3:
    15. return []
    16. for i in range(len(nums)):
    17. map[nums[i]] = i
    18. threelist = []
    19. # print(map) {-4: 0, -1: 2, 0: 3, 1: 4, 2: 5}
    20. for i in range(0, len(nums) - 2):
    21. x = nums[i]
    22. if x > 0: break
    23. if i > 0 and nums[i - 1] == nums[i]: continue
    24. for j in range(i + 1, len(nums) - 1):
    25. y = nums[j]
    26. if x + y > 0: break
    27. if j > i + 1 and nums[j - 1] == nums[j]: continue
    28. z = 0 - x - y
    29. if z in map.keys() and map.get(z) > j:
    30. threelist.append([x, y, z])
    31. return threelist
    32. test = Solution()
    33. nums = [-1, 0, 1, 2, -1, -4]
    34. re = test.threeSum(nums)
    35. print(re)

    3. 优化(排序 + 双指针

    1. """
    2. Time:2022/11/23 22:51
    3. Author:ECCUSYB
    4. """
    5. class Solution(object):
    6. def threeSum(self, nums):
    7. """
    8. :type nums: List[int]
    9. :rtype: List[List[int]]
    10. """
    11. n = len(nums)
    12. if not nums or n < 3:
    13. return []
    14. nums.sort()
    15. res = []
    16. for i in range(n):
    17. # 如果第一个值大于零,直接返回空
    18. if nums[i] > 0:
    19. return res
    20. # 如果当前值等于上一个值,跳过,进入下一次循环,去除重复值
    21. if i > 0 and nums[i] == nums[i - 1]:
    22. continue
    23. L = i + 1
    24. R = n - 1
    25. while (L < R): # 如果 L>R 或者 L=R 就结束
    26. if nums[i] + nums[L] + nums[R] == 0:
    27. res.append([nums[i], nums[L], nums[R]])
    28. while L < R and nums[L] == nums[L + 1]:
    29. L = L + 1
    30. while L < R and nums[R] == nums[R - 1]:
    31. R = R - 1
    32. L = L + 1
    33. R = R - 1
    34. # 如果三数之和大于零,就将R--
    35. elif nums[i] + nums[L] + nums[R] > 0:
    36. R = R - 1
    37. else:
    38. L = L + 1
    39. return res
    40. test = Solution()
    41. nums = [-1, 0, 1, 2, -1, -4]
    42. re = test.threeSum(nums)
    43. print(re)

  • 相关阅读:
    岛屿问题 通用解-463.岛屿周长-200.岛屿数量
    如何创建高效的 Python Docker 镜像详解
    血清与血浆
    MFC 1.获取文件路径 2.获取文件夹路径 3.获取程序根目录
    burp改返回包(Burp Suite抓包使用步骤)
    数据结构第三遍补充(图的应用)
    XML解析
    9.25day5---Qt
    python barplot 比例bili scanpy
    SpringBoot整合Druid配置yml文件
  • 原文地址:https://blog.csdn.net/weixin_42322991/article/details/128015419