Skip to content

Commit affba32

Browse files
committed
add 3sum solution
1 parent c5ccea0 commit affba32

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed

3sum/jongwanra.py

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
"""
2+
[Problem]
3+
https://leetcode.com/problems/3sum/description/
4+
5+
[Brainstorm]
6+
3 <= nums.length <= 3,000
7+
Brute Force: O(N^3) => 27,000,000,000 => time limited
8+
O(N^2)의 풀이는 시간 제한에 걸리지 않을 것으로 보인다. 3,000 * 3,000 => 9,000,000
9+
10+
[Plan]
11+
1. map을 설정한다. key = elements value: index list
12+
2. nested-loop을 순회한다.
13+
2-1. i == j인 경우 제외
14+
2-2. map에서 동일한 인덱스인 경우 제외하고 구한다.
15+
16+
"""
17+
18+
from typing import List
19+
20+
21+
class Solution:
22+
"""
23+
Attempt-1 My solution (incorrect)
24+
time limited
25+
"""
26+
27+
def threeSum1(self, nums: List[int]) -> List[List[int]]:
28+
map = {}
29+
for index in range(len(nums)):
30+
values = map.get(nums[index], [])
31+
values.append(index)
32+
map[nums[index]] = values
33+
34+
triplets = set()
35+
for i in range(len(nums)):
36+
for j in range(len(nums)):
37+
if i == j:
38+
continue
39+
complement = -(nums[i] + nums[j])
40+
# print(f"nums[{i}]={nums[i]}, nums[{j}]={nums[j]} , complement={complement}")
41+
if complement in map:
42+
values = map[complement]
43+
for k in values:
44+
if k == i or k == j:
45+
continue
46+
triplets.add(tuple(sorted([nums[i], nums[j], nums[k]])))
47+
return list(triplets)
48+
49+
"""
50+
Attempt-2 Another solution
51+
ref: https://www.algodale.com/problems/3sum/
52+
53+
"""
54+
55+
def threeSum2(self, nums: List[int]) -> List[List[int]]:
56+
triplets = set()
57+
58+
for index in range(len(nums) - 2):
59+
seen = set()
60+
for j in range(index + 1, len(nums)):
61+
complement = -(nums[index] + nums[j])
62+
if complement in seen:
63+
triplet = [nums[index], nums[j], complement]
64+
triplets.add(tuple(sorted(triplet)))
65+
seen.add(nums[j])
66+
67+
return list(triplets)
68+
69+
"""
70+
Attempt-3 Another solution
71+
ref: https://www.algodale.com/problems/3sum/
72+
73+
[Plan]
74+
two-pointer로 접근한다.
75+
76+
[Complexity]
77+
N: nums.length
78+
Time: O(N^2)
79+
Space: O(1)
80+
"""
81+
82+
def threeSum3(self, nums: List[int]) -> List[List[int]]:
83+
triplets = set()
84+
nums.sort()
85+
86+
for index in range(len(nums) - 2):
87+
left = index + 1
88+
right = len(nums) - 1
89+
90+
while left < right:
91+
three_sum = nums[index] + nums[left] + nums[right]
92+
if three_sum < 0:
93+
left += 1
94+
continue
95+
if three_sum > 0:
96+
right -= 1
97+
continue
98+
triplets.add((nums[index], nums[left], nums[right]))
99+
left += 1
100+
right -= 1
101+
return list(triplets)
102+
103+
104+
sol = Solution()
105+
print(sol.threeSum3([-1, 0, 1, 2, -1, 4]))
106+

0 commit comments

Comments
 (0)