374.猜数字大小

https://leetcode-cn.com/problems/guess-number-higher-or-lower/

二分法

class Solution:
    def guessNumber(self, n: int) -> int:
        l = 1
        r = n
        while l <= n:
            mid = l + (r - l) // 2
            if guess(mid) == -1:
                r = mid - 1
            elif guess(mid) == 1:
                l = mid + 1
            else:
                return mid
        return l
        

最后更新于