15.三数之和
说明
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
题解思路
排序+双指针
如果满足条件,添加到输出数组
代码实现
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
ans = []
nums.sort()
n = len(nums)
for a in range(n - 2):
if a > 0 and nums[a] == nums[a-1]:
continue
c = n - 1
tar = -nums[a]
for b in range(a+1, n - 1):
if b > a + 1 and nums[b] == nums[b - 1]:
continue
while b < c and nums[b] + nums[c] > tar:
c -= 1
if b == c:
break
if nums[b] + nums[c] == tar:
ans.append([nums[a], nums[b], nums[c]])
return ans