-
-
Notifications
You must be signed in to change notification settings - Fork 421
/
ThreeNumbersSum.py
54 lines (39 loc) · 1.08 KB
/
ThreeNumbersSum.py
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
46
47
48
49
50
51
52
53
54
"""
15. 3Sum
Medium
8121
881
Add to List
Share
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Example 2:
Input: nums = []
Output: []
Example 3:
Input: nums = [0]
Output: []
"""
def sum_of_three(arr, target=0) :
result = list()
arr.sort()
for i in range(len(arr)-2) :
left = i+1;right=len(arr)-1
while left < right :
current_sum = arr[i] + arr[left] + arr[right]
if current_sum == target :
result.append((arr[i], arr[left], arr[right]))
left+=1
right-=1
elif current_sum < target :
left += 1
elif current_sum > target :
right -= 1
else :
print("Dont with the loop")
return result
if __name__ == '__main__' :
print(sum_of_three([3,5,-4,8,11,1,-1,6]))