-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy path259_3Sum_Smaller.py
56 lines (54 loc) · 1.75 KB
/
259_3Sum_Smaller.py
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
class Solution(object):
# def threeSumSmaller(self, nums, target):
# """
# :type nums: List[int]
# :type target: int
# :rtype: int
# """
# # https://leetcode.com/articles/3sum-smaller/#approach-2-binary-search-accepted
# nums.sort()
# ls = len(nums)
# res = 0
# for i in range(ls - 1):
# res += self.twoSumSmaller(nums, i + 1, target - nums[i])
# return res
#
# def twoSumSmaller(self, nums, start, target):
# res = 0
# for i in range(start, len(nums)):
# pos = self.binarySearch(nums, i, target - nums[i])
# res += pos - i
# return res
#
# def binarySearch(self, nums, start, target):
# left, right = start, len(nums) - 1
# while left < right:
# mid = (left + right + 1) / 2
# if nums[mid] < target:
# # left should always less than target
# left = mid
# else:
# right = mid - 1
# return left
def threeSumSmaller(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# https://leetcode.com/articles/3sum-smaller/#approach-2-binary-search-accepted
nums.sort()
ls = len(nums)
res = 0
for i in range(ls - 1):
res += self.twoSumSmaller(nums, i + 1, target - nums[i])
return res
def twoSumSmaller(self, nums, start, target):
res, left, right = 0, start, len(nums) - 1
while left < right:
if nums[left] + nums[right] < target:
res += right - left
left += 1
else:
right -= 1
return res