[LeetCode]Guess Number Higher or Lower

题目描述:

LeetCode 374. Guess Number Higher or Lower

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'll tell you whether the number is higher or lower.

You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):

-1 : My number is lower
 1 : My number is higher
 0 : Congrats! You got it!

Example:

n = 10, I pick 6.

Return 6.

题目大意:

我们来玩猜数字游戏。游戏规则如下:

我挑选一个1到n之间的数字。你来猜我选的是哪个数字。

每一次你猜错,我都会告诉你数字高了还是低了。

你可以调用一个预定义的API guess(int num),返回3种结果 (-1, 1, 或 0):

-1 : 我的数字更低
 1 : 我的数字更高
 0 : 恭喜你!猜对了!

测试用例如题目描述。

解题思路:

二分查找(Binary Search)

Python代码:

# 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(object):
    def guessNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        left, right = 1, n
        while left <= right:
            mid = (left + right) >> 1
            trial = guess(mid)
            if trial == -1:
                right = mid - 1
            elif trial == 1:
                left = mid + 1
            else:
                return mid

 

本文链接:http://bookshadow.com/weblog/2016/07/13/leetcode-guess-number-higher-or-lower/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码