• 【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)

  • 相关阅读:
    C++中的回调函数再次总结(std::bind和function)
    E2. Salyg1n and Array (hard version) Codeforces Round 897 (Div. 2)
    h5开发网站-页面内容不够高时,如何定位footer始终位于页面的最底部
    如何形象简单地理解java中只有值传递,而没有引用传递?
    Flask框架——基于Celery的后台任务
    for...in 和 for...of 的区别
    八月开始备考MBA/MPA/MEM,慌不慌?
    三分钟带你了解AD20中的3D元器件如何改变显示色彩
    The given SOAPAction http__xxxxx_xx does not match an operation
    随机产生一个1-100之间的整数,看能几次猜中
  • 原文地址:https://blog.csdn.net/weixin_42322991/article/details/128015419