题目链接 | 2563. 统计公平数对的数目 |
---|---|
思路 | 排序+二分(upper_bound - lower_bound) |
题解链接 | 两种方法:二分查找 / 三指针(Python/Java/C++/Go) |
关键点 | 排序并不影响答案(数对数量未变化) |
时间复杂度 | \(O(n\log n)\) |
空间复杂度 | \(O(1)\) |
代码实现:
class Solution:
def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:
nums.sort()
def upper_bound(val, lo, hi):
while lo + 1 < hi:
mid = (lo+hi)//2
if nums[mid] > val:
hi = mid
else:
lo = mid
return hi
def lower_bound(val, lo, hi):
while lo + 1 < hi:
mid = (lo+hi)//2
if nums[mid] < val:
lo = mid
else:
hi = mid
return hi
answer = 0
for j, x in enumerate(nums):
r = upper_bound(upper-x, -1, j)
l = lower_bound(lower-x, -1, j)
answer += r-l
return answer
Python-标准库
class Solution:
def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:
nums.sort()
answer = 0
for j, x in enumerate(nums):
r = bisect_right(nums, upper-x, 0, j)
l = bisect_left(nums, lower-x, 0, j)
answer += r-l
return answer