
难度不小![]()
注意是不能重复

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]: continuefor j in range(i, n):if j > (i+1) and nums[j - 1] == nums[j]: continuefor k in range(j, n):if k > (j + 1) and nums[k - 1] == nums[k]: continueif 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 threelisttest = 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]] = ithreelist = []# 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: breakif i > 0 and nums[i - 1] == nums[i]: continuefor j in range(i + 1, len(nums) - 1):y = nums[j]if x + y > 0: breakif j > i + 1 and nums[j - 1] == nums[j]: continuez = 0 - x - yif z in map.keys() and map.get(z) > j:threelist.append([x, y, z])return threelisttest = 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]:continueL = i + 1R = n - 1while (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 + 1while L < R and nums[R] == nums[R - 1]:R = R - 1L = L + 1R = R - 1# 如果三数之和大于零,就将R--elif nums[i] + nums[L] + nums[R] > 0:R = R - 1else:L = L + 1return restest = Solution()
nums = [-1, 0, 1, 2, -1, -4]
re = test.threeSum(nums)print(re)
上一篇:儿子生日祝福语用微信怎么发