题目描述
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a ,b ,c ,使得 a + b + c = 0 ?请找出所有和为 0 且 不重复 的三元组。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/1fGaJU
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
方法
此题为剑指 Offer II 006. 排序数组中两个数字之和的升级版。因此我们需要在两个数字和的基础上再增加一层for循环,然后利用双指针确定剩余两个数。
当n < 3时,直接返回空。
由于要删除重复的三元组,因此我们首先对数组进行排序,然后用for循环定第一个数first,用双指针second和third定后两个数。
特殊处理:
我们利用 in 判断是否当前求得的三元组已经存在于ans数组中。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
ans = []
n = len(nums)
if n < 3:
return []
nums = sorted(nums)
for first in range(n-2):
if first > 0 and nums[first] == nums[first-1]:
continue
res = -nums[first]
second = first + 1
third = n - 1
while second < third:
target = nums[second] + nums[third]
if target == res:
#重复三元组判断操作
if not [nums[first], nums[second], nums[third]] in ans:
ans.append([nums[first], nums[second], nums[third]])
second += 1
third -= 1
elif target > res:
third -= 1
else:
second += 1
return ans