4
头图

Guess the size of the number

Title description: The rules of the number guessing game are as follows:

  • In each round of the game, I randomly choose a number from 1 to n. Please guess which number was selected.
  • If you guess wrong, I will tell you whether the number you guessed is larger or smaller than the number I selected.

You can get the guess result by calling a predefined interface int guess(int num). The return value has 3 possible situations (-1, 1 or 0):

  • -1: The number I selected is smaller than the number you guessed by pick <num
  • 1: The number I selected is larger than the number you guessed by pick> num
  • 0: The number I selected is the same as the number you guessed. Congratulations! you guessed right! pick == num

Return the number I selected.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/guess-number-higher-or-lower/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Binary search method

For a typical binary search problem, the initial value of low is 1, and the initial value of high is num. The binary search process is as follows:

  • The premise of the loop is that low is not greater than high;
  • Then the value of mid is low + (high - low) / 2 , and then the method guess(num) is called to judge;
  • If it returns -1, the value of high is set to mid - 1 , and then the next round of processing is performed;
  • If it returns 1, the value of low is set to mid + 1 , and then the next round of processing is performed;
  • If it returns 0, it returns the mid value, which is the selected number.
public class LeetCode_374 extends GuessGame {
    /**
     * 二分查找
     *
     * @param num
     * @return
     */
    public static int guessNumber(int num) {
        int low = 1, high = num;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (guess(mid) == -1) {
                high = mid - 1;
            } else if (guess(mid) == 0) {
                return mid;
            } else if (guess(mid) == 1) {
                low = mid + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(guessNumber(2126753390));
    }
}


class GuessGame {
    /**
     * 假设1702766719是最终的结果
     * Forward declaration of guess API.
     *
     * @param 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
     */
    public static int guess(int num) {
        if (num > 1702766719) {
            return -1;
        } else if (num == 1702766719) {
            return 0;
        } else {
            return 1;
        }
    }
}
[Daily Message] In short, it has been a long time, but it is worth the wait.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!