Leetcode374. Guess Number Higher or Lower

本文介绍了一种使用二分查找法解决猜数字游戏问题的方法,该方法能够在对数时间内找到正确答案。通过定义的guess函数反馈,逐步缩小搜索范围直至找到目标数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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.
思路:
要求:使用对数的时间复杂度来完成本题目。我从1-n中选出一个数,然后对方来猜,如果对方猜不中,就告诉对方我的数是比他的数高还是低;注意guess函数是返回1,0,-1的值。使用二分查找法注意溢出的情况,使用 mid=(j-i)/2+i;而不使用mid=(j+i)/2,数字太大就会导致溢出
代码:
/* The guess API is defined in the parent class GuessGame.
   @param num, your guess
   @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
      int guess(int num); */


public class Solution extends GuessGame {
    public int guessNumber(int n) {
        int i=1;
        int j=n;
        int mid=0;
        //使用二分法查找
        while(i<=j){
            //求中间数
            mid=(j-i)/2+i;
            //guess(int num)是用来返回目标值比你猜的这个数是高了还是低了
            int val=guess(mid);
            //-1表示我的数字比你猜的数字要小
            if(val==-1)
            j=mid-1;
            else if(val==1)
            //+1表示我的数字比你猜的数字要大
                i=mid+1;
                else 
                return mid;
        }
        
        return -1;
    }
}
原题地址
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值