# LeetCode 374. Guess Number Higher or Lower [374. Guess Number Higher or Lower](leetcode_url) (難度 通過率) <!-- (<font color=#00AF9B>Easy</font> 53.8%) (<font color=#FFB800>Medium</font> 39.6%) (<font color=#FF375F>Hard</font>) --> - 限制 : <ul> <li><code>1 <= n <= 2³¹ - 1</code></li> <li><code>1 <= pick <= n</code></li> </ul> - Solution 沒特別變化的 binary search。 - 時間複雜度: $O(lg(n))$ - 空間複雜度: $O(1)$ - 程式碼 ```c++= /** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number * 1 if num is lower than the picked number * otherwise return 0 * int guess(int num); */ class Solution { public: int guessNumber(int n) { int min_index = 0, max_index = n; while(min_index <= max_index) { int mid_index = (max_index - min_index) / 2 + min_index; if(guess(mid_index) == 0) return mid_index; if(guess(mid_index) == 1) min_index = mid_index + 1; if(guess(mid_index) == -1) max_index = mid_index - 1; } return -1; } }; ``` </details>