Skip to content

Latest commit

 

History

History
39 lines (33 loc) · 918 Bytes

0374._guess_number_higher_or_lower.md

File metadata and controls

39 lines (33 loc) · 918 Bytes

Navigation

Links

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

Solution 1 二分

# 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):

class Solution:
    def guessNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        left = 1
        right = n

        while left <= right:
            mid = (left + right) // 2
            flag = guess(mid)

            if flag == -1:
                # 猜大了
                right = mid - 1
            elif flag == 1:
                # 猜小了
                left = mid + 1
            else:
                return mid