Title Description:
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.
Problem Solving Ideas:
Variants of the binary lookup method
The code is as follows:
# The Guess API is already defined for you.# @param num, your guess# @return-1 If my number was lower, 1 if my number is H Igher, otherwise return 0# def guess (num): Class solution (Object): def guessnumber (self, N): "" " : Type N:int : Rtype:int "" "left, right = 1, n while (left <= right): mid = (left + right)/2 res = guess ( MID) if res = = 0: return mid elif res = =-1: Right = mid-1 elif res = = 1: Left = mid + 1
return-1
Python [leetcode 374]guess number Higher or Lower