2300. 咒语和药水的成功对数

题目链接 2300. 咒语和药水的成功对数
思路 排序+二分
题解链接 排序 + 二分(Python/Java/C++/Go/JS/Rust)
关键点 \(xy\ge s \Rightarrow y\ge \lceil \frac{s}{x} \rceil \Rightarrow y > \lfloor \frac{s-1}{x} \rfloor\)
时间复杂度 \(O((n+m)\log m)\)
空间复杂度 \(O(1)\)

代码实现:

class Solution:
    def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:
        potions.sort()
        m = len(potions)

        # 开区间
        def upper_bound(val):
            left, right = -1, m
            while left + 1 < right:
                # 循环不变式
                # nums[left] <= val
                # nums[right] > val
                mid = (left+right) // 2
                if potions[mid] > val:
                    right = mid
                else:
                    left = mid
            return right



        success -= 1
        return [
            m - upper_bound(success // x) for x in spells
        ]
Python-标准库
class Solution:
    def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:
        potions.sort()
        m = len(potions)
        success -= 1
        return [
            m - bisect_right(potions, success // x) for x in spells
        ]
posted @ 2024-09-09 22:15  WrRan  阅读(19)  评论(0)    收藏  举报