Skip to content

Commit 8a9360a

Browse files
Create three_sum.py
1 parent 6abfbde commit 8a9360a

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
def threesum(arr, target):
2+
res = []
3+
arr.sort()
4+
5+
length = len(arr)
6+
7+
for i in range(length -2):
8+
if i > 0 and arr[i] == arr[i-1]:
9+
continue
10+
l = i +1
11+
r = length -1
12+
13+
while l < r:
14+
total = arr[i] + arr[l] + arr[r]
15+
16+
if total < target:
17+
l += 1
18+
elif total > target:
19+
r -=1
20+
else:
21+
res.append([arr[i],arr[l],arr[r]])
22+
while l < r and arr[l] == arr[l+1]:
23+
l += 1
24+
while l < r and arr[r] == arr[r-1]:
25+
r -= 1
26+
27+
l +=1
28+
r -=1
29+
return res
30+
31+
print(threesum([-1,0,1,2,-1,-4],0))
32+
33+
34+
35+
36+

0 commit comments

Comments
 (0)