-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0259-3sum-smaller.py
More file actions
35 lines (30 loc) · 919 Bytes
/
0259-3sum-smaller.py
File metadata and controls
35 lines (30 loc) · 919 Bytes
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
# time complexity: O(n^2)
# space completity: O(1)
from typing import List
class Solution:
def threeSumSmaller(self, nums: List[int], target: int) -> int:
result = 0
nums.sort()
for i in range(len(nums) - 1):
result += self.twoSumSmaller(nums, i + 1, target - nums[i])
return result
def twoSumSmaller(self, nums: List[int], startIdx: int, target: int) -> int:
left = startIdx
right = len(nums) - 1
result = 0
while left < right:
if nums[left] + nums[right] < target:
result += right - left
left += 1
else:
right -= 1
return result
nums = [-2, 0, 1, 3]
target = 2
print(Solution().threeSumSmaller(nums, target))
nums = []
target = 0
print(Solution().threeSumSmaller(nums, target))
nums = [0]
target = 0
print(Solution().threeSumSmaller(nums, target))