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 (-11, 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.

题意:

给定数字n和某个在1-n之间的位置数x,系统已经定义好了函数guess(),当guess(x)返回0,则猜中,当guess(x)返回-1,则你猜的数字比给定的数字大了,当guess(x)返回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(object):
    def guessNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        
        low = 1
        high = n
        while guess((low+high)/2) != 0 and low < high :             #如果没猜中且low<high,则继续循环来猜
            if guess((low+high)/2) == -1 :                               #你猜的数字猜高了,将high降低
                high = (low+high)/2 - 1
            else :
                if guess((low+high)/2) == 1 :                       #你猜的数字猜低了,将low升高
                    low = (low+high)/2 + 1
        return (low+high)/2                    


笔记:

这类题的下标变换,老是需要用调试代码才能理清楚

if guess((low+high)/2) == 1 :                       #你猜的数字猜低了,将low升高
           low = (low+high)/2 + 1

此处,如果改成 low = (low+high)/2  ,则会进入死循环(例如n=2,给定2,则low总是1)

调试了之后,才知道要写成low = (low+high)/2+1(排除 (low+high)/2仍等于low或high的情况,避免进入死循环)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值