2563. 統計公平數對的數目

WrRan發表於2024-09-09
題目連結 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

相關文章