374. Guess Number Higher or Lower [easy] (Python)

题目链接

https://leetcode.com/problems/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中挑选一个数,你来猜我挑的数是多少。每次你猜错了我都会告诉你正确数字是更大还是更小。
你写的函数可以调用一个预先实现的guess(int num)的接口,它能返回-1,0,1三个可能值:-1表示正确数字更小;1表示正确数字更大;0表示猜对了。
比如:当n=10,我选的数是6时,你的函数也应该返回6。

思路方法

本题的关键是理解题意。。。

思路一

这个游戏大部分人都玩过,二分搜索解决即可。

代码

# 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 True:
            mid = (left + right) / 2
            if guess(mid) == 1:
                left = mid + 1
            elif guess(mid) == -1:
                right = mid - 1
            else:
                return mid

思路二

将上面的代码改造成递归算法。

代码

# 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
        """
        return self.guessIn(1, n)

    def guessIn(self, left, right):
        mid = (left + right) / 2
        if guess(mid) == 0:
            return mid
        else:
            return self.guessIn(left, mid-1) if guess(mid) == -1 else self.guessIn(mid+1, right)

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/52038995

你可能感兴趣的:(LeetCode,LeetCode解题报告)