Leetcode每日一题2021/01/20

二分法继续…
Leetcode每日一题2021/01/20_第1张图片
Leetcode每日一题2021/01/20_第2张图片
3

# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:

class Solution:
    def guessNumber(self, n: int) -> int:
        left, right = 1, n
        while(left <= right):       # [1, n]
            mid = (right+left)>>1
            flag = guess(mid)
            if(flag == 0):
                break
            elif(flag == -1):
                right = mid - 1     # [left, mid-1]
            elif(flag == 1):
                left = mid + 1      # [mid+1, right]
        return mid

Leetcode每日一题2021/01/20_第3张图片

你可能感兴趣的:(Leetcode,leetcode,二分法,算法)