374. Guess Number Higher or Lower
Difficulty: Easy
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.
思路
二分查找。
需要注意数据类型,mid = (lower + higher) / 2时,lower + higher可能超出取值范围,数据类型不能为int,若非要用int,则应用以下方式:mid = lower + (higher - lower) / 2。
代码
[C++]
class Solution {
public:
int guessNumber(int n) {
int lower = 1;
int higher = n;
while (lower <= higher) {
int mid = lower + (higher - lower) / 2;
int res = guess(mid);
if (res == 0)
return mid;
else if (res == 1)
lower = mid + 1;
else
higher = mid - 1;
}
return -1;
}
};
本文介绍了一种简单而有效的猜数字游戏算法——二分查找法。通过预定义的API反馈来判断所猜数字与目标数字的高低关系,最终确定正确答案。文章详细解释了二分查找的具体实现过程,并注意到了在计算中间值时避免整数溢出的问题。
723

被折叠的 条评论
为什么被折叠?



