We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.

You call a pre-defined API int guess(int num), which returns three possible results:

-1: Your guess is higher than the number I picked (i.e. num > pick).
1: Your guess is lower than the number I picked (i.e. num < pick).
0: your guess is equal to the number I picked (i.e. num == pick).

Return the number that I picked.

Example 1:

Input: n = 10, pick = 6
Output: 6

Example 2:

Input: n = 1, pick = 1
Output: 1

Example 3:

Input: n = 2, pick = 1
Output: 1

Constraints:

1 <= n <= 231 - 1
1 <= pick <= n

https://leetcode.cn/problems/guess-number-higher-or-lower/description/
方法一:二分查找

记选出的数字为 pick,猜测的数字为 x。根据题目描述,若 guess(x)≤0 则说明 x≥pick,否则 x<pick。

根据这一性质我们可以使用二分查找来求出答案 pick。

二分时,记当前区间为 [left,right],初始时 left=1,right=n。记区间中间元素为 mid,若有 guess(mid)≤0 则说明 pick∈[left,mid],否则 pick∈[mid+1,right]。当区间左右端点相同时,则说明我们找到了答案,退出循环。

class Solution:
    def guessNumber(self, n: int) -> int:
        left, right = 1, n
        while left < right:
            mid = (left + right) // 2
            if guess(mid) <= 0:
                right = mid   # 答案在区间 [left, mid] 中
            else:
                left = mid + 1   # 答案在区间 [mid+1, right] 中
        
        # 此时有 left == right,区间缩为一个点,即为答案
        return left

更多推荐