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.
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 :
Input: n = 10, pick = 6
Output: 6
Ideas of solving problems
The question is to compare the size of the Numbers to see if they are the right answer.We guess the Numbers by dichotomy.Compared with enumeration, dichotomy takes less time and is more effective.The traversal distance can be shortened by half by dichotomy.My first attempt was with enumeration, but the time was out of scope.Therefore, using dichotomy, can effectively reduce the running time. The time complexity is O(n), and space complexity is O(n). The memory consumption is 2Mb.
Code
func guessNumber(n int) int {
a , b := 1, n
for a < b {
mid := a + (b - a) / 2
if guess(mid) == 0{
return mid
}else if guess(mid) == 1{
a = mid + 1
}else{
b = mid - 1
}
}
return a
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/guess-number-higher-or-lower