Method 1:
T O(n^2), S:O(n)
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
Dict = {}
res = []
nums.sort()
print(nums)
n = len(nums)
for i, ele in enumerate(nums):
Dict[ele] = i
i = 0
while(i < n-2):
ele1 = nums[i]
j = i+1
while(j < n-1):
ele2 = nums[j]
remain = 0 - (ele1 + ele2)
if remain in Dict and Dict[remain] > j:
res.append([ele1, ele2, remain])
while(j+1 < n-1 and nums[j] == nums[j+1]):
j+=1
j+=1
while(i+1 < n-2 and nums[i] == nums[i+1]):
i+=1
i+=1
return res
Method 2:
T O(n^2), S:O(1)
cclass Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
i = 0
while i < (len(nums) - 2):
target = -nums[i]
l = i+1
r = len(nums) - 1
while(l<r):
l_flag = nums[l]
r_flag = nums[r]
if nums[l] + nums[r] > target:
while(l < r and nums[r] == r_flag):
r-=1
elif nums[l] + nums[r] < target:
while(l < r and nums[l] == l_flag):
l+=1
else:
res.append([nums[i], nums[l], nums[r]])
while(l < r and nums[l] == l_flag):
l+=1
while(r > l and nums[r] == r_flag):
r-=1
i_flag = nums[i]
while(i < len(nums) -2 and nums[i] == i_flag):
i+=1
return res