forked from alqamahjsr/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path259_3Sum_Smaller.py
More file actions
33 lines (28 loc) · 990 Bytes
/
259_3Sum_Smaller.py
File metadata and controls
33 lines (28 loc) · 990 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
class Solution(object):
def threeSumSmaller(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
triplateCount = 0
for i in range(len(nums) - 2):
left, right = i + 1, len(nums) - 1
while left < right:
currentSum = nums[i] + nums[left] + nums[right]
if currentSum < target:
triplateCount += (right - left) # if (i,j,k) works, then (i,j,k), (i,j,k-1),...,(i,j,j+1) all work, totally (k-j) triplets
left += 1
else:
while left < right and nums[right] == nums[right - 1]: # Duplication check
right -= 1
right -= 1
return triplateCount
sol = Solution()
# input = [3,1,0,-2]
# target = 4
input = [-2,0,1,3]
target = 2
tripletsNum = sol.threeSumSmaller(input, target)
print("Result: ", tripletsNum)