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; } } } };
相关文章推荐
- 单例-lintcode-c++
- 字符串置换-lintcode-c++
- 174. 删除链表中倒数第n个节点 (remove-nth-node-from-end-of-list)(c++)----lintcode面试题之链表
- 回文数-lintcode-c++
- 451. 两两交换链表中的节点(swap-nodes-in-pairs)(c++)----lintcode面试题之链表
- 165. 合并两个排序链表(merge-two-sorted-lists)(c++)----lintcode面试题之链表
- LintCode 452.删除链表中的元素 C++
- 35. 翻转链表(reverse-linked-list)(c++)----lintcode面试题之链表
- [LintCode]Sort Integers(C++)
- 372. 在O(1)时间复杂度删除链表节点 (delete-node-in-the-middle-of-singly-linked-list)(c++)----lintcode面试题之链表
- LintCode 466.链表节点计数 C++
- lintcode 843. 数字翻转 个人想法及C++代码
- 166. 链表倒数第n个节点(nth-to-last-node-in-list)(c++)----lintcode面试题之链表
- [LintCode]Binary Tree Maximum Node(C++)
- LintCode_208 Assignment Operator Overloading (C++ Only)
- 用c++编的猜数游戏(文曲星里那种猜数游戏)
- [LintCode]Compare Strings(C++|Python)
- LintCode-6合并排序数组 II(C++)
- 猜数游戏C++
- 112. 删除排序链表中的重复元素(remove-duplicates-from-sorted-list)(c++)----lintcode面试题之链表