您的位置:首页 > 产品设计 > UI/UE

LeetCode-374. Guess Number Higher or Lower

2018-03-24 15:23 246 查看

Description

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.


Solution 1(C++)

// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);

class Solution {
public:
int guessNumber(int n) {
int high=n, low=1, gnum=(high-low)/2+low;
for(; guess(gnum)!=0; gnum=(high-low)/2+low){
if(guess(gnum)==1) low=gnum+1;
else if(guess(gnum)==-1) high=gnum-1;
}
return gnum;
}
};


Solution 2(C++)

// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);

class Solution {
public:
int guessNumber(int n) {
int maxNumber = n, minNumber = 1;
while (true) {
int meanNumber = (maxNumber - minNumber) / 2 + minNumber;
// Do NOT use (maxNumber+minNumber)/2 in case of over flow
int res = guess(meanNumber);
if (res == 0) {
return meanNumber;
} else if (res == 1) {
minNumber = meanNumber + 1;
} else {
maxNumber = meanNumber - 1;
}
}
}
};


算法分析

二分查找,简单的逻辑能掌握,只是一点小技巧,二分查找上下限每次更新的时候不能只更新为中间值,而应该是中间值+-1。比如解法一与解法二中的更新high时更新为gnum-1,更新low时更新为gnum+1。

程序分析

很重要的就是(maxNumber - minNumber) / 2 + minNumber,这一句。防止过拟合。然后这道题比较坑的就是,阅读理解了。

-1 : My number is lower
1 : My number is higher
0 : Congrats! You got it!

Here “My” means the number which is given for you to guess not the number you put into guess(int num).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: