We are playing the Guess Game. The game is as follows:
I pick a number from 1 to N. You had 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 = ten, I pick 6.Return 6.
This question is a typical guessing price problem, according to the other side said high or low to narrow the range, the simplest and fastest way is binary search method, the principle is very simple, see the code is as follows:
//Forward Declaration of the Guess API.//@param num, your guess//@return-1 If my number is lower, 1 if my number is higher, otherwise return 0intGuessintnum);classSolution { Public: intGuessnumber (intN) {if(guess (n) = =0)returnN; intleft =1, right =N; while(Left <Right ) { intMid = left + (right-left)/2, t =guess (mid); if(T = =0)returnmid; Else if(T = =1) left =mid; Elseright =mid; } returnLeft ; }};
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Guess number Higher or Lower