Skip to content

Commit 2000b54

Browse files
committed
- 3Sum DaleStudy#241
1 parent f98f5b2 commit 2000b54

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

3sum/ayosecu.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
- Algorithm
6+
- Sort and compares with three pointers: target, left(l), right(r)
7+
- Time Complexity: O(n^2), n = len(nums)
8+
- sort : O(nlogn)
9+
- nested two loops : O(n^2)
10+
- O(nlogn + n^2) => O(n^2)
11+
- Space Complexity: O(n^2) if result included.
12+
- result size : result.append() called in n^2 times (nested two loops)
13+
"""
14+
def threeSum(self, nums: List[int]) -> List[List[int]]:
15+
result = []
16+
nums.sort()
17+
18+
n = len(nums)
19+
for i in range(n - 2):
20+
# skip duplicated numbers
21+
if i > 0 and nums[i] == nums[i - 1]:
22+
continue
23+
24+
target = nums[i]
25+
l, r = i + 1, n - 1
26+
while l < r:
27+
if nums[l] + nums[r] == -target:
28+
result.append([target, nums[l], nums[r]])
29+
# skip duplicated numbers
30+
while l < r and nums[l] == nums[l + 1]:
31+
l += 1
32+
while l < r and nums[r] == nums[r - 1]:
33+
r -= 1
34+
l += 1
35+
r -= 1
36+
elif nums[l] + nums[r] < -target:
37+
l += 1
38+
else:
39+
r -= 1
40+
41+
return result
42+
43+
tc = [
44+
([-1,0,1,2,-1,-4], [[-1,-1,2],[-1,0,1]]),
45+
([0,1,1], []),
46+
([0,0,0], [[0,0,0]])
47+
]
48+
49+
for i, (nums, e) in enumerate(tc, 1):
50+
sol = Solution()
51+
r = sol.threeSum(nums)
52+
print(f"TC {i} is Passed!" if e == r else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

0 commit comments

Comments
 (0)