algos_and_structures/algocode/hash_tables/3sum.py

36 lines
1.1 KiB
Python

from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
sorted = nums.sort()
result = []
for i in range(0, len(nums) - 2):
if i > 0 and nums[i] == nums[i-1]:
i += 1
continue
j = i + 1
k = len(nums) - 1
first_num = nums[i]
while j < k:
second_num = nums[j]
third_num = nums[k]
tmp_sum = first_num + second_num + third_num
if tmp_sum < 0:
j += 1
elif tmp_sum > 0:
k -= 1
elif tmp_sum == 0:
j += 1
result.append([first_num, second_num, third_num])
while nums[j-1] == nums[j] and j < k:
j += 1
else:
raise ValueError("Some strange shit happened")
i += 1
return result
cl = Solution()
print(cl.threeSum(nums=[-1,0,1,2,-1,4]))
print(cl.threeSum(nums=[0,0,0]))
print(cl.threeSum(nums=[0,0,0,0]))