Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of z
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
#三個數字
if len(nums) <3:
return []
len1 = len(nums)-1
nums = sorted(nums)
l1 = []
for i in range(len1-1):
if i > 0 and nums[i] == nums[i-1]: continue
left = i+1
right = len1
if nums[i] > 0:
break
while left<right:
checked = nums[i] + nums[right] + nums[left]
if checked == 0:
l1.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 checked <0:
left+=1
else:
right-=1
return l1