[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; } } };