题目描述:
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组
例子:
给定数组 nums
= [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路分析:本题目与之前的两数之和相似,但是如果用暴力解决的办法,时间复杂度为O(N^3)而且在leetcode中容易超时,因此本题采用双指针法。
首先先排除一下特例的情况如数组的元素长度小于3或者空数组,在接着对数组进行排序,如果最小的元素都大于0,不存在三数之和为0。我们将左指针设为i+1,右指针len(nums)-1,如果存在三数之和为0,则左右指针各向右移动,接着需要判断该数的附近是否有重复,进行去重,各自指针进行移动。如果三数之和大于0,右指针左移,左指针右移。
代码展示
class Solution
(object
):
def threeSum
(self
, nums
):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
n=len
(nums
)
ans=
[]
if n<3 or nums==None:
return []
ans=
[]
nums
.sort()
for i in range
(n
):
if nums
[i]>0:
return ans
if i>0 and nums
[i]==nums
[i-1]:
continue
L=i
+1
R=n
-1
while L<R:
if nums
[i]+nums
[L]+nums
[R]==0:
ans
.append
([nums[i],nums[L],nums[R]])
while(L<R and nums
[L]==nums
[L+1]):
L=L
+1
while(L<R and nums
[R]==nums
[R-1]):
R=R
-1
L=L
+1
R=R
-1
elif nums
[i]+nums
[L]+nums
[R]>0:
R=R
-1
else:
L=L
+1
return ans