-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15_3Sum.py
More file actions
45 lines (27 loc) · 1.25 KB
/
15_3Sum.py
File metadata and controls
45 lines (27 loc) · 1.25 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 15. 3Sum
# Nick White's solution: https://www.youtube.com/watch?v=qJSPYnS35SE
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
triplets = []
if len(nums)<3:
return triplets
nums = sorted(nums)
for i in range(len(nums)-2):
low = i+1
high = len(nums)-1
twoSum = -nums[i]
while(low<high):
if nums[low]+nums[high]==twoSum:
if [nums[i], nums[low], nums[high]] not in triplets:
triplets.append([nums[i], nums[low], nums[high]])
while(low<high and nums[low]==nums[low+1]):
low+=1
while(low<high and nums[high]==nums[high-1]):
high-=1
low = low+1
high = high-1
elif nums[low]+nums[high]>twoSum:
high-=1
else:
low+=1
return triplets