给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。 注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
提示:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
方法一:(两数之和对等于负的第三数)
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
res = []
nums.sort()
for left in range(n):
if left > 0 and nums[left] == nums[left-1]:
continue
target = -nums[left]
right = n-1
for mid in range(left+1, n):
if mid > left+1 and nums[mid] == nums[mid-1]:
continue
while mid < right and nums[mid] + nums[right] > target:
right -= 1
if mid == right:
break
if nums[mid] + nums[right] == target:
res.append([nums[left], nums[mid], nums[right]])
return res
方法二:(直接双指针)
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
res = []
if not nums and n < 3:
return []
nums.sort()
for left in range(n-2):
if nums[left] > 0:
break
if left > 0 and nums[left] == nums[left-1]:
continue
mid = left + 1
right = n-1
while mid < right:
if nums[mid] + nums[left] + nums[right] < 0:
mid += 1
while mid < right and nums[mid] == nums[mid - 1]:
mid += 1
elif nums[mid] + nums[left] + nums[right] > 0:
right -= 1
while nums[right] == nums[right+1]:
right -= 1
else:
res.append([nums[left], nums[mid], nums[right]])
mid += 1
right -= 1
while mid < right and nums[mid] == nums[mid-1]:
mid += 1
while mid < right and nums[right] == nums[right+1]:
right -= 1
return res
|