前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:374. Guess Number Higher or Lower

LeetCode笔记:374. Guess Number Higher or Lower

作者头像
Cloudox
发布2021-11-23 15:37:32
2400
发布2021-11-23 15:37:32
举报
文章被收录于专栏:月亮与二进制月亮与二进制

问题:

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) ,它会返回三个可能的结果 (-1, 1, or 0): -1 : 我的数字更小 1 : 我的数字更大 0 : 恭喜!猜中了! 例子: n = 10, 我选 6. 返回6.

思路:

这道题题目主动提示了用二分法来做,所以只用把二分法的思想写出来,根据每次猜测得到的大了或者小了的结果来进行分别处理。猜小了就在大的那个区间去继续取中间数字猜,猜大了就在小的那个区间取中间数字猜,因为取中间数字猜整体来说是最快的,为了记录区间,还要保留上次猜的情况,来让区间越缩越小。

代码(Java):

代码语言:javascript
复制
/* 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) {
        return helper(1,n);
    }
    
    public int helper(int start, int end){
        if(start == end) return start;
        int mid = Math.toIntExact(((long)start+(long)end)/2);
        int r = 0;
        if(guess(mid) == 0) r = mid;
        else if(guess(mid) == 1) r = helper(mid+1, end);
        else if(guess(mid) == -1) r = helper(start, mid-1);
        return r;
    }
}

合集:https://github.com/Cloudox/LeetCode-Record

查看作者首页

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/11/22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题:
  • 大意:
  • 思路:
  • 代码(Java):
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档