Skip to content

Commit 60eaa7e

Browse files
committed
Time: 413 ms (88.42%), Space: 18.1 MB (37.73%) - LeetHub
1 parent 005c4c7 commit 60eaa7e

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# time complexity: O(n^2)
2+
# space completity: O(1)
3+
from typing import List
4+
5+
6+
class Solution:
7+
def threeSumSmaller(self, nums: List[int], target: int) -> int:
8+
result = 0
9+
nums.sort()
10+
for i in range(len(nums) - 1):
11+
result += self.twoSumSmaller(nums, i + 1, target - nums[i])
12+
return result
13+
14+
def twoSumSmaller(self, nums: List[int], startIdx: int, target: int) -> int:
15+
left = startIdx
16+
right = len(nums) - 1
17+
result = 0
18+
while left < right:
19+
if nums[left] + nums[right] < target:
20+
result += right - left
21+
left += 1
22+
else:
23+
right -= 1
24+
return result
25+
26+
27+
nums = [-2, 0, 1, 3]
28+
target = 2
29+
print(Solution().threeSumSmaller(nums, target))
30+
nums = []
31+
target = 0
32+
print(Solution().threeSumSmaller(nums, target))
33+
nums = [0]
34+
target = 0
35+
print(Solution().threeSumSmaller(nums, target))

0 commit comments

Comments
 (0)