From 95d668400d89a642deb0c8c86c46b00d11435523 Mon Sep 17 00:00:00 2001 From: ADITYA DUBEY <75172576+adidubs@users.noreply.github.com> Date: Sat, 1 Oct 2022 20:42:42 +0530 Subject: [PATCH] Update three_sum.py --- algorithms/arrays/three_sum.py | 59 +++++++++++++++------------------- 1 file changed, 26 insertions(+), 33 deletions(-) diff --git a/algorithms/arrays/three_sum.py b/algorithms/arrays/three_sum.py index ccf3d2669..923b70e8d 100644 --- a/algorithms/arrays/three_sum.py +++ b/algorithms/arrays/three_sum.py @@ -13,36 +13,29 @@ (-1, -1, 2) } """ - - -def three_sum(array): - """ - :param array: List[int] - :return: Set[ Tuple[int, int, int] ] - """ - res = set() - array.sort() - for i in range(len(array) - 2): - if i > 0 and array[i] == array[i - 1]: - continue - l, r = i + 1, len(array) - 1 - while l < r: - s = array[i] + array[l] + array[r] - if s > 0: - r -= 1 - elif s < 0: - l += 1 - else: - # found three sum - res.add((array[i], array[l], array[r])) - - # remove duplicates - while l < r and array[l] == array[l + 1]: - l += 1 - - while l < r and array[r] == array[r - 1]: - r -= 1 - - l += 1 - r -= 1 - return res +''' used two pointer apporach''' + +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + sol = [] + nums.sort() + + for i in range(len(nums)-2): + first= i + left = i+1 + right = len(nums)-1 + + while left < right: + + if nums[first] + nums[left] + nums[right] == 0: + if ([nums[first] , nums[left] , nums[right]]) not in sol: + sol.append([nums[first] , nums[left] , nums[right]]) + right -=1 + left +=1 + + elif nums[first] + nums[left] + nums[right] > 0: + right -=1 + + elif nums[first] + nums[left] + nums[right] < 0: + left +=1 + return sol