Skip to content

Commit 5093ab9

Browse files
3sum
1 parent 1e97028 commit 5093ab9

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

solution.py

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]]
2+
# such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
3+
#
4+
# Notice that the solution set must not contain duplicate triplets.
5+
#
6+
#
7+
# Example 1:
8+
#
9+
# Input: nums = [-1,0,1,2,-1,-4]
10+
# Output: [[-1,-1,2],[-1,0,1]]
11+
# Explanation:
12+
# nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
13+
# nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
14+
# nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
15+
# The distinct triplets are [-1,0,1] and [-1,-1,2].
16+
# Notice that the order of the output and the order of the triplets does not matter.
17+
18+
19+
nums = [-1,0,1,2,-1,-4]
20+
21+
def threesum(nums):
22+
# for i in nums:
23+
# for j in nums:
24+
# for k in nums:
25+
# if i + j + k == 0:
26+
# print(f"{i} + {j} + {k} = 0")#
27+
# brute force for fun
28+
#
29+
# dic_nums = {}
30+
# for i, v in enumerate(nums):
31+
# dic_nums[i] = v
32+
#
33+
#
34+
# po1, po2 = 0, 1
35+
#
36+
#
37+
# while po2 < len(nums) -1:
38+
# # if nums[left] + nums[right] == dic -value == 0
39+
# iter = nums[po1] + nums[po2]
40+
# listofsums = []
41+
#
42+
# for k, v in dic_nums.items():
43+
# if iter + v == 0:
44+
# listofsums.append([nums[po1], nums[po2], nums[k]])
45+
#
46+
# po1 += 1
47+
# po2 += 1
48+
#
49+
# return listofsums
50+
51+
nums.sort()
52+
i = 0
53+
left, right = i+1, len(nums)-1
54+
arr = []
55+
56+
while i < len(nums) - 2:
57+
if nums[i] + nums[left] + nums[right] == 0:
58+
res = [nums[i], nums[left], nums[right]]
59+
arr.append(res)
60+
i += 1
61+
left += 1
62+
right -= 1
63+
64+
65+
66+
return arr
67+
68+
69+
70+
71+
72+
73+
74+
print(threesum(nums))

0 commit comments

Comments
 (0)