Skip to content

Commit c997a78

Browse files
authored
Update 3Sum - Leetcode 15.py
1 parent 0cfa37c commit c997a78

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

3Sum - Leetcode 15/3Sum - Leetcode 15.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# Hashmap Solution:
12
class Solution:
23
def threeSum(self, nums: List[int]) -> List[List[int]]:
34
h = {}
@@ -17,3 +18,34 @@ def threeSum(self, nums: List[int]) -> List[List[int]]:
1718

1819
# Time Complexity: O(n^2)
1920
# Space Complexity: O(n)
21+
22+
23+
## Two Pointer Solution:
24+
class Solution:
25+
def threeSum(self, nums: List[int]) -> List[List[int]]:
26+
nums.sort()
27+
n = len(nums)
28+
answer = []
29+
for i in range(n):
30+
if nums[i] > 0:
31+
break
32+
elif i > 0 and nums[i] == nums[i-1]:
33+
continue
34+
lo, hi = i+1, n-1
35+
while lo < hi:
36+
summ = nums[i] + nums[lo] + nums[hi]
37+
if summ == 0:
38+
answer.append([nums[i], nums[lo], nums[hi]])
39+
lo, hi = lo+1, hi-1
40+
while lo < hi and nums[lo] == nums[lo-1]:
41+
lo += 1
42+
while lo < hi and nums[hi] == nums[hi+1]:
43+
hi -= 1
44+
elif summ < 0:
45+
lo += 1
46+
else:
47+
hi -= 1
48+
49+
return answer
50+
# Time: O(n^2)
51+
# Space: O(n) (Excluding the output)

0 commit comments

Comments
 (0)