[leetcode]374. Guess Number Higher or Lower

匿名 (未验证) 提交于 2019-12-03 00:30:01

[leetcode]374. Guess Number Higher or Lower


Analysis

雨很大~―― [ummm~]

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.

类似于猜价格的题,二分查找解决。

Implement

// 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) {         if(guess(n) == 0)             return n;         int lo = 1;         int hi = n;         int mid;         while(lo < hi){             mid = lo + (hi - lo) / 2;             if(guess(mid) == 0)                 return mid;             else if(guess(mid) == -1)                 hi = mid;             else if(guess(mid) == 1)                 lo = mid;         }     } };
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!