您的位置:首页 > 编程语言 > C语言/C++

LintCode-662. 猜数游戏(C++)

2017-12-20 15:35 483 查看

题目描述:

我们正在玩猜数游戏。 游戏如下:

我从 1 到 n 选择一个数字。 你需要猜我选择了哪个号码。

每次你猜错了,我会告诉你这个数字是高还是低。

你调用一个预定义的接口 guess(int num),它会返回 3 个可能的结果(-1,1或0):

原始代码:

// 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:
/**
* @param n an integer
* @return the number you guess
*/
int guessNumber(int n) {
// Write your code here
}
};


分析:

这道题其实可以看成一个查找算法(查找那个你要猜的数)。在这里我用的折半查找(平均时间复杂度为O(log2n))

第一次尝试:

// 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:
/**
* @param n an integer
* @return the number you guess
*/
int guessNumber(int n) {
// Write your code here
int low = 1, high = n;
while(low < high) {
int mid = (low + high) / 2;
int r = guess(mid);
if(r == 1) {
low = mid + 1;
} else if(r == -1) {
high = mid - 1;
} else {
return mid;
}
}
}
};


运行之后显示错误Time Limit Exceeded,然后显示的测试数据是2147483647,而这个数就是int型数据能储存的最大的数。这是因为
low + high
会出现超出int型数据类型存储范围,导致超限的数字变成负数进而造成死循环。



所以做一下修改:

// 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:
/**
* @param n an integer
* @return the number you guess
*/
int guessNumber(int n) {
// Write your code here
int low = 1, high = n;
while (low < high) {
int mid = low + (high - low)/2; //这样就OK了!
int r = guess(mid);
if(r == 1) {
low = mid + 1;
} else if(r == -1) {
high = mid - 1;
} else {
return mid;
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  刷题