給定一個包含 n 個整數(shù)的數(shù)組 nums
椎侠,判斷 nums
中是否存在三個元素 a滩租,b巢掺,c 淆九,使得 a + b + c = 0 ?找出所有滿足條件且不重復的三元組配猫。
注意: 答案中不可以包含重復的三元組幅恋。
例如, 給定數(shù)組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為:
[
[-1, 0, 1],
[-1, -1, 2]
]
CODE:
class Solution:
def threeSum(self, nums):
nums.sort() # 先排序
n = len(nums)
left = 0
right = n - 1
results = []
# 固定一個數(shù)泵肄,另外2個數(shù)從兩邊夾捆交,3個數(shù)的和大于0,右邊最大值就減少腐巢,如果小于0品追,左右最大值就增加
# 固定數(shù)如果相同的話(因為排序位置會在一起),結(jié)果可能會相同冯丙,所以直接跳過
for index in range(0, n):
if index >= 1 and nums[index] == nums[index - 1]:
continue
# 左邊從固定數(shù)右邊最小值開始肉瓦,右邊從最大值開始
left, right = index + 1, n - 1
while left < right:
total = nums[left] + nums[index] + nums[right]
if total == 0:
results.append([nums[index], nums[left], nums[right]])
# 如果和為0,左右各前進一步胃惜,如果只變left,right其中一個泞莉,由于left,index固定,3個數(shù)和固定船殉,那么right肯定固定鲫趁,所以左右都要變
left += 1
right -= 1
# 左右前進的時候,如果前進后的值和原值相同則需要繼續(xù)前進捺弦,不然會重復
# 如:[-2, 0, 0, 2, 2]饮寞,a: index(0,1,4), b:index(0, 2, 3)都是[-2,0,2]會重復
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif total > 0:
right -= 1
else:
left += 1
return results
su = Solution()
nums = [-2, 0, 0, 2, 2]
res = su.threeSum(nums)
print(res)