Given an integer array nums,
return all the triplets [nums[i], nums[j], nums[k]]
such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
주어진 정수 배열에 대해서 세 원소를 뽑아 triplet을 만들때, 각 원소의 합이 0이 되는 쌍들을 구해
배열로 만들어 리턴하시오
중복된 triplet은 있어선 안됩니다.
Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
ans = []
for target in range(0, len(nums)-2):
if target != 0 and nums[target-1] == nums[target]: continue
left = target + 1
right = len(nums) - 1
while left < right and right > target:
if nums[target] + nums[left] + nums[right] == 0:
ans.append([nums[target], nums[left], nums[right]])
while left != len(nums)-1 and nums[left + 1] == nums[left]: left += 1
left += 1
while right != target+1 and nums[right - 1] == nums[right]: right -= 1
right -= 1
elif nums[target] + nums[left] + nums[right] < 0:
while left != len(nums)-1 and nums[left + 1] == nums[left]: left += 1
left += 1
else:
while right != target+1 and nums[right - 1] == nums[right]: right -= 1
right -= 1
return ans