题目信息
算法思想
三数之和的思想和两数之和的差不多
1、将numbers进行排序,然后先固定一个数numbers[i]
2、再设置j=i+1,k=len(numbers)-1
3、当j<k时,执行循环:
判断numbers[i]+numbers[j]+numbers[k]=0
将numbers[i],numbers[j],numbers[k]添加到要返回的列表
去重:判断numbers[j]=numbers[j+1],如果相等,跳过当前重复的值
判断numbers[k]=numbers[k-1],如果相等,跳过当前重复的值
如果和大于0,则k-1
如果和小于0,则j+1
代码实现
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
if not nums or n < 3:
return []
nums.sort()
listout = []
for i in range(n):
if nums[i] > 0:
return listout
if i > 0 and nums[i] == nums[i - 1]:
continue
j = i + 1
k = n - 1
while j < k:
if nums[i] + nums[j] + nums[k] == 0:
list_1 = [nums[i], nums[j], nums[k]]
listout.append(list_1)
while j < k and nums[j] == nums[j + 1]:
j += 1
while j < k and nums[k] == nums[k - 1]:
k -= 1
j = j + 1
k -= 1
elif nums[i] + nums[j] + nums[k] > 0:
k -= 1
else:
j += 1
return listout