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
Example 1
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
ans = []
for i in range(n - 2):
for j in range(i + 1, n - 1):
for k in range(j + 1, n):
if not (i != j and i != k and j != k):
continue
if nums[i] + nums[j] + nums[k] == 0:
tmpAns = [nums[i], nums[j], nums[k]]
# to remove duplicate ans
tmpAns.sort()
if tmpAns not in ans:
ans += [tmpAns]
return ans
Time Complexity: O(N^3)
Space Complexity: O(N)
TODO
Time Complexity: O(N^2)
Space Complexity: O(N)
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
n = len(nums)
ans = []
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
l, r = i + 1, n - 1
while l < r:
threeSum = nums[i] + nums[l] + nums[r]
if threeSum > 0:
r -= 1
elif threeSum < 0:
l += 1
else:
ans += [[nums[i], nums[l], nums[r]]]
l += 1
# to ignore duplicate ans
while l < r and nums[l] == nums[l - 1]:
l += 1
return ans
Time Complexity: O(N^2)
Space Complexity: O(1)
https://leetcode.com/problems/3sum/discuss/2589188/100-Best-Solution-Explained
TODO
Time Complexity: O()
Space Complexity: O()
TODO
Time Complexity: O()
Space Complexity: O()