forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEgonD3V.py
More file actions
76 lines (58 loc) ยท 2.37 KB
/
EgonD3V.py
File metadata and controls
76 lines (58 loc) ยท 2.37 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from typing import List
from unittest import TestCase, main
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
return self.solveWithTwoPointer(nums)
"""
Runtime: 691 ms (Beats 62.42%)
Time Complexity: O(n^2)
- nums๋ฅผ ์ ๋ ฌํ๋๋ฐ O(n * log n)
- ์ฒซ index๋ฅผ ์ ํ๊ธฐ ์ํด range(len(nums) - 2) ์กฐํํ๋๋ฐ O(n - 2)
- i + 1 ๋ถํฐ n - 1๊น์ง lo, hi ํฌํฌ์ธํฐ ์กฐํํ๋๋ฐ, i๊ฐ ์ต์๊ฐ์ธ 0์ธ ๊ฒฝ์ฐ๋ฅผ upper bound๋ก ๊ณ์ฐํ๋ฉด O(n - 1)
> O(n * log n) + O(n - 2) * O(n - 1) ~= O(n * log n) + O(n^2) ~= O(n^2)
Memory: 20.71 MB (Beats 30.94%)
Space Complexity:
- num๋ ์ ๋ ฌํ๊ธด ํ๋๋ฐ ์๊ธฐ์์ ๊ทธ๋๋ก ์ฌ์ฉํ๋ฏ๋ก ๊ณ์ฐ ์ธ
> lo๋ hi๋ triplet_sum์ input์ ์ํฅ์๋ ํฌ๊ธฐ์ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋ฏ๋ก O(1)
"""
def solveWithTwoPointer(self, nums: List[int]) -> List[List[int]]:
nums.sort()
triplets = []
for i in range(len(nums) - 2):
if 1 <= i and nums[i] == nums[i - 1]:
continue
lo, hi = i + 1, len(nums) - 1
while lo < hi:
triplet_sum = nums[i] + nums[lo] + nums[hi]
if triplet_sum < 0:
lo += 1
elif triplet_sum > 0:
hi -= 1
else:
triplets.append([nums[i], nums[lo], nums[hi]])
while lo < hi and nums[lo] == nums[lo + 1]:
lo += 1
while lo < hi and nums[hi] == nums[hi - 1]:
hi -= 1
lo += 1
hi -= 1
return triplets
class _LeetCodeTestCases(TestCase):
def test_1(self):
nums = [-1, 0, 1, 2, -1, -4]
output = [[-1, -1, 2], [-1, 0, 1]]
self.assertEqual(Solution.threeSum(Solution(), nums), output)
def test_2(self):
nums = [0, 1, 1]
output = []
self.assertEqual(Solution.threeSum(Solution(), nums), output)
def test_3(self):
strs = [0, 0, 0]
output = [[0, 0, 0]]
self.assertEqual(Solution.threeSum(Solution(), strs), output)
def test_4(self):
strs = [0, 0, 0, 0, 0, 0, 0, 0]
output = [[0, 0, 0]]
self.assertEqual(Solution.threeSum(Solution(), strs), output)
if __name__ == '__main__':
main()