leetcode-374-Guess Number Higher or Lower(二分查找)
Posted chenjx85
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 (-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.
要完成的函数:
int guess(int num);//api函数
int guessNumber(int n)
说明:
1、给定一个整数 n,从1到n中挑一个数出来,让你猜是哪个数。每次你猜一个数,调用一次api函数,返回0就代表刚好是这个数,你猜对了!如果返回-1,就表示你猜的数太大了,实际的数比这个小。如果返回1,就表示你猜的数太小了,实际的数比这个大。要求最终返回对的那个数。
2、这道题很明显是一道二分查找的题目,手工写一个二分查找的代码。
代码如下:(附详解)
int guess(int num);
int guessNumber(int n)
{
int low=1,high=n,mid,t;
while(low<=high)
{
mid=low+(high-low)/2;//写成 mid=(low+high)/2 可能会上溢
t=guess(mid);
if(t==0)
return mid;
else if(t==-1)//实际的数比mid小
high=mid-1;
else //实际的数比mid大
low=mid+1;
}
}
上述代码实测2ms,beats 100.00% of cpp submissions。
以上是关于leetcode-374-Guess Number Higher or Lower(二分查找)的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 374. Guess Number Higher or Lower
Leetcode 374. Guess Number Higher or Lower
leetcode 374. Guess Number Higher or Lower
LeetCode 374 Guess Number Higher or Lower