Guess Number Higher or Lower – LeetCode 374
Problem
Description
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):
Example
n = 10, I pick 6.
Return 6.
Answer
Original
Code
1 | // Forward declaration of guess API. |
思路
简单使用二分查找。时间复杂度$O(log_{2}{n})$,空间复杂度$O(1)$。
耗时$2$ ms,排名$81.30\%$
Better
思路
看到题解中有三分查找。时间复杂度$O(log_{3}{n})$,空间复杂度$O(1)$。
耗时$2$ ms,排名$81.30\%$
Code
1 | // Forward declaration of guess API. |