给定一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ]
思路:
直接用二数之和的hashmap解法加额外的一层循环会超时在CASE311,
尝试使用普通的双指针在有序数组里找两数之和加额外的一层循环还是会超时在case311,
学习了一波答案,发现由于case太大,所以需要在最外层循环去重。
if i == 0 or nums[i] > nums[i - 1]:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
#固定a,用双指针在排序数组里找两数之和为-a
nums.sort()
l = len(nums)
res = []
for i, a in enumerate(nums):
if i == 0 or nums[i] > nums[i - 1]:
#开始双指针
left, right = i + 1, len(nums) - 1
while(left < right):
s = a + nums[left] + nums[right]
if s == 0:
tmp = [a, nums[left], nums[right]]
res.append(tmp)
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while right > left and nums[right] == nums[right + 1]:
right -= 1
elif s < 0:
left += 1
elif s > 0:
right -= 1
return res