15. 三数之和
给定一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ]
解题思路:先对数组进行排序,然后从前向后遍历数组,值nums[i]作为三数的第一个数字。对于上述的每一个数字,在其后面的子数组中查找能使条件-nums[i] == nums[left] + nums[right]满足的nums[left],nums[right]。若条件满足,则将三个数字加入到结果列表中;若nums[left] + nums[right] > -nums[i],则right -= 1;若nums[left] + nums[right] < -nums[i],则left += 1。
注意:题目要求答案中不可以包含重复的三元组,因此需要有两处判断重复的代码。
Python3代码如下:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
nums = sorted(nums)
for i in range(len(nums)-2):
if i and nums[i-1] == nums[i]:# 重复
continue
left,right = i+1,len(nums)-1
while left < right:
if nums[left] + nums[right] == -nums[i]:
result.append([nums[i],nums[left],nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left-1]:# 重复
left += 1
while left < right and nums[right] == nums[right+1]:
right -= 1
elif nums[left] + nums[right] < -nums[i]:
left += 1
else:
right -= 1
return result