我们正在玩一个猜数字游戏。 游戏规则如下: 我从 1 到 n 选择一个数字。 你需要猜我选择了哪个数字。 每次你猜错了,我会告诉你这个数字是大了还是小了。 你调用一个预先定义好的接口 guess(int num),它会返回 3 个可能的结果(-1,1 或 0): -1 : 我的数字比较小 1 : 我的数字比较大 0 : 恭喜!你猜对了! 复制代码
示例:
输入: n = 10, pick = 6 输出: 6 复制代码
思考:
这题与二分查找类似,同样是二分查找方法,通过已有的guess接口来返回大小,大于中间数向右查找,小于中间数向左查找。 复制代码
实现:
public class Solution extends GuessGame {
public int guessNumber(int n) {
int low = 1;
int high = n;
int num = 0;
while (low <= high) {
num = low + (high - low) / 2;
if (guess(num) == 0) {
return num;
} else if (guess(num) == -1) {
high = num - 1;
} else if (guess(num) == 1) {
low = num + 1;
}
}
return num;
}
}复制代码
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Writing Apache Modules with Perl and C
Lincoln Stein、Doug MacEachern / O'Reilly Media, Inc. / 1999-03 / USD 39.95
Apache is the most popular Web server on the Internet because it is free, reliable, and extensible. The availability of the source code and the modular design of Apache makes it possible to extend Web......一起来看看 《Writing Apache Modules with Perl and C》 这本书的介绍吧!