forked from GeeksforGeeks-VIT-Bhopal/GeekWeek-Local
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDAY4program 1- 3sum.py
More file actions
27 lines (21 loc) · 956 Bytes
/
DAY4program 1- 3sum.py
File metadata and controls
27 lines (21 loc) · 956 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
def twosum_helper(target, results, nums, left, right, num):
while left < right:
if nums[left] + nums[right] < target:
left += 1
elif nums[left] + nums[right] > target:
right -= 1
else:
triplet = [num, nums[left], nums[right]]
if triplet not in results:
results.append(triplet)
left += 1
results = []
if len(nums) < 3:
return results
nums = sorted(nums)
for i, num in enumerate(nums):
target = -num
twosum_helper(target, results, nums, i + 1, len(nums) - 1, num)
return results