Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✅374. 猜数字大小 #80

Open
Ray-56 opened this issue Aug 4, 2020 · 1 comment
Open

✅374. 猜数字大小 #80

Ray-56 opened this issue Aug 4, 2020 · 1 comment
Labels

Comments

@Ray-56
Copy link
Owner

Ray-56 commented Aug 4, 2020

374. 猜数字大小

猜数字游戏的规则如下:

每轮游戏,系统都会从 1 到 n 随机选择一个数字。 请你猜选出的是哪个数字。
如果你猜错了,系统会告诉你这个数字比系统选出的数字是大了还是小了。
你可以通过调用一个预先定义好的接口 guess(int num) 来获取猜测结果,返回值一共有 3 种可能的情况(-1,1 或 0):

-1 : 系统选出的数字比你猜测的数字小
 1 : 系统选出的数字比你猜测的数字大
 0 : 恭喜!你猜对了!

示例:

输入: n = 10, pick = 6
输出: 6
@Ray-56 Ray-56 added the 简单 label Aug 4, 2020
@Ray-56
Copy link
Owner Author

Ray-56 commented Aug 5, 2020

二分查找解

题意不好理解,理解后就是一个二分查找

/** 
 * Forward declaration of guess API.
 * @param {number} num   your guess
 * @return 	            -1 if num is lower than the guess number
 *			             1 if num is higher than the guess number
 *                       otherwise return 0
 * var guess = function(num) {}
 */

/**
 * @param {number} n
 * @return {number}
 */
var guessNumber = function(n) {
    let left = 1;
    let right = n;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        const midVal = guess(mid);
        if (midVal === 0) return mid;
        if (midVal === -1) {
            right = mid - 1;
        } else if (midVal === 1) {
            left = mid + 1;
        }
    }
};

@Ray-56 Ray-56 changed the title 374. 猜数字大小 ✅374. 猜数字大小 Aug 13, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant