Skip to content

Commit 91950a3

Browse files
authored
Create 2563.py
1 parent ab4b66c commit 91950a3

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

python3/2563.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution:
2+
def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:
3+
# trivial case
4+
if len(nums) < 2:
5+
return 0
6+
7+
def findM(target, l, r):
8+
while l < r:
9+
m = (l + r) // 2
10+
if nums[m] < target:
11+
l = m + 1
12+
else:
13+
r = m
14+
return l
15+
16+
res = 0
17+
nums.sort()
18+
l, r = -1, len(nums) - 1
19+
while l + 2 <= r:
20+
l += 1
21+
if nums[l] + nums[r] < lower:
22+
continue
23+
m = findM(lower - nums[l], l + 1, r)
24+
while r >= m and nums[l] + nums[r] > upper:
25+
r -= 1
26+
if l < m and m <= r:
27+
res += r - m + 1
28+
return res

0 commit comments

Comments
 (0)