Leetcode 15. 三数之和
题目说明
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
题目解析
-
数组双指针法
对数组进行排序。
遍历数组,对于每次遍历,对没有遍历的后续元素设置左右指针。
将每次遍历的元素与左右指针的元素相加,看是否为0,小于0则左指针右移,大于0则右指针左移。
等于0的情况较为复杂,可能会出现指针后续元素与当前元素相同的情况,需要排除掉。然后左右指针都往里移动。剪枝操作
当遍历的元素大于0(则后续元素全部大于0,不能等于0,可能有[0,0,0,0,0,0]的情况),return
当遍历的元素与之前的元素相同时,continue
Python代码
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums = sorted(nums)
resultList = []
for i in range(len(nums) - 2):
if nums[i] > 0:
break
if i > 0 and nums[i] == nums[i - 1]:
continue
l, r = i + 1, len(nums) - 1
while l < r:
if nums[i] + nums[l] + nums[r] == 0:
resultList.append([nums[i], nums[l], nums[r]])
while l < r and nums[l] == nums[l + 1]:
l += 1
while l < r and nums[r] == nums[r - 1]:
r -= 1
l += 1
r -= 1
elif nums[i] + nums[l] + nums[r] < 0:
l += 1
else:
r -= 1
return resultList