给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[ [-1, 0, 1], [-1, -1, 2] ]
思路:
- 对数组进行排序,利用有序数组的性质设置三指针。
i
为当前指针,low=i+1
,high=len(nums)-1
- 三指针元素和相加为
ans=nums[i]+nums[low]+nums[high]
- 这时候若
ans=0
,则三指针符合题意,将其加入结果列表。但题目要求不能取重复值,有序列表中,重复元素是连续的,因此循环执行low=low+1
,high=high-1
, 直到两指针相遇或出现不同的元素。 - 若
ans>0
,此时说明high偏大,根据 滑动窗口的思想,high指针左移。 - 同理若
ans<0
,low指针右移。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
l=[]
for i in range(0,len(nums)):
if nums[i]>0:
break
low=i+1
high=len(nums)-1
# 消除重复
if i>0 and nums[i]==nums[i-1] :
continue
while low<high:
ans=nums[i]+nums[low]+nums[high]
if(ans==0):
l.append([nums[i],nums[low],nums[high]])
while (low<high and nums[low]==nums[low+1]):
low+=1
while (low<high and nums[high]==nums[high-1]):
high-=1
low+=1
high-=1
elif ans>0:
high=high-1
elif ans<0:
low+=1
return l