Skip to content

Commit 738f1a0

Browse files
committed
leetcode.com 15. 3Sum v2
문제 링크: https://leetcode.com/problems/3sum/
1 parent 17d381f commit 738f1a0

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

leetcode.com 15. 3Sum v2/main.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def threeSum(self, nums: List[int]) -> List[List[int]]:
6+
nums.sort()
7+
myset = set()
8+
9+
for idx_left in range(0, len(nums) - 2):
10+
target = -nums[idx_left]
11+
idx_mid = idx_left + 1
12+
idx_right = len(nums) - 1
13+
14+
while idx_mid < idx_right:
15+
if nums[idx_mid] + nums[idx_right] == target:
16+
myset.add((nums[idx_left], nums[idx_mid], nums[idx_right]))
17+
idx_mid += 1
18+
idx_right -= 1
19+
elif nums[idx_mid] + nums[idx_right] < target:
20+
idx_mid += 1
21+
elif nums[idx_mid] + nums[idx_right] > target:
22+
idx_right -= 1
23+
24+
return [list(item) for item in list(myset)]

leetcode.com 15. 3Sum v2/test_main.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from unittest import TestCase
2+
from main import Solution
3+
4+
5+
class TestSolution(TestCase):
6+
def test_three_sum(self):
7+
sln = Solution()
8+
self.assertEqual(sln.threeSum([-1,0,1,2,-1,-4]), [[-1,0,1], [-1,-1,2]])
9+
10+
def test_three_sum2(self):
11+
sln = Solution()
12+
self.assertEqual(sln.threeSum([0, 1, 1]), [])
13+
14+
def test_three_sum3(self):
15+
sln = Solution()
16+
self.assertEqual(sln.threeSum([0, 0, 0]), [[0, 0, 0]])
17+
18+
def test_three_sum4(self):
19+
sln = Solution()
20+
self.assertEqual(sln.threeSum([1,-1,-1,0]), [[-1, 0, 1]])

0 commit comments

Comments
 (0)