Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 374. Guess Number Higher or Lower

Rain Hu

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 will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num), which returns three possible results:

Example 1:

Example 2:

Example 3:

Constraints:


二、分析

bool BinarySearch(int x, int lo, int hi) {
    while (lo <= hi) {
        int mid = lo + (hi - lo)/2;
        if (API(mid) == 0) {
            return true;
        } else if (API(mid) > 0) {  // 往左收斂
            right = mid-1;
        } else if (API(mid) < 0) {  // 往右收斂
            left = mid+1;
        }
        return false
    }
}

三、解題

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

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 223. Rectangle Area
Next
[LeetCode] 213. House Robber II