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.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Example 2:
Input: nums = []
Output: []
Example 3:
Input: nums = [0]
Output: []
세 개의 수를 더해서 0이 되는 것은 크게 3가지로 나뉠 수 있다.
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
if len(nums) < 3:
return []
counts = {}
for num in nums:
counts[num] = counts[num] + 1 if num in counts else 1
cases = []
if counts.get(0):
if counts[0] >= 3:
cases = [[0,0,0]]
nums = list(sorted(counts.keys()))
for i in range(len(nums)):
if counts.get(nums[i]) > 1 and nums[i] != 0:
if counts.get(-nums[i] * 2):
cases.append([nums[i], nums[i], -2 * nums[i]])
for j in range(i+1, len(nums)):
if counts.get(-nums[i]-nums[j]):
if nums[j] >= -nums[i]-nums[j]:
break
else:
cases.append([nums[i], nums[j], -nums[i]-nums[j]])
return cases