[LeetCode] 374. Guess Number Higher or Lower 猜數字大小


 

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 (-11, or 0):

-1 : My number is lower
 1 : My number is higher
 0 : Congrats! You got it!

Example:

n = 10, I pick 6.

Return 6.

 

這道題是一道典型的猜價格的問題,根據對方說高了還是低了來縮小范圍,雖然是道 Easy 題,無腦線性遍歷還是會超時 Time Limit Exceeded,所以更快速的方法就是折半搜索法,原理很簡單,屬於博主之前的總結帖 LeetCode Binary Search Summary 二分搜索法小結 中的第四類-用子函數當作判斷關系,參見代碼如下:

 

int guess(int num);

class Solution {
public:
    int guessNumber(int n) {
        if (guess(n) == 0) return n;
        int left = 1, right = n;
        while (left < right) {
            int mid = left + (right - left) / 2, t = guess(mid);
            if (t == 0) return mid;
            if (t == 1) left = mid + 1;
            else right = mid;
        }
        return left;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/374

 

類似題目:

Guess Number Higher or Lower II 

First Bad Version

Find K Closest Elements

 

參考資料:

https://leetcode.com/problems/guess-number-higher-or-lower/

https://leetcode.com/problems/guess-number-higher-or-lower/discuss/84664/0ms-c%2B%2B-binary-search

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM