• 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 :

    Input: n = 10, pick = 6
    Output: 6

    M1: binary search

    time = O(log_2(n)), space = O(1)

    /* The guess API is defined in the parent class GuessGame.
       @param num, your guess
       @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
          int guess(int num); */
    
    public class Solution extends GuessGame {
        public int guessNumber(int n) {
            int left = 1, right = n;
            while(left <= right) {
                int mid = left + (right - left) / 2;
                int res = guess(mid);
                if(res == 0) {
                    return mid;
                } else if(res == -1) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            }
            return -1;
        }
    }

    M2: ternary search

    In Ternary Search, we choose two pivots (say m1 and m2) such that the given range is divided into three equal parts. If the required number (num) is less than m1, then we apply ternary search on the left segment of m1. If num lies between m1 and m2, we apply ternary search between m1 and m2. Otherwise we will search in the segment right to m2.

    time = O(log_3(n)), space = O(1)

    public class Solution extends GuessGame {
        public int guessNumber(int n) {
            int left = 1, right = n;
            while(left <= right) {
                int mid1 = left + (right - left) / 3;
                int mid2 = right - (right - left) / 3;
                int res1 = guess(mid1);
                int res2 = guess(mid2);
                if(res1 == 0) {
                    return mid1;
                } else if(res2 == 0) {
                    return mid2;
                } else if(res1 == -1) {
                    right = mid1 - 1;
                } else if(res2 == 1) {
                    left = mid2 + 1;
                } else {
                    left = mid1 + 1;
                    right = mid2 - 1;
                }
            }
            return -1;
        }
    }
  • 相关阅读:
    【转】用微软的Live Writer离线写新浪博文
    【转】充满想象力的 Web 调色板
    【转】安装Windows Live Writer后需要做的五件事
    【转】Form Design 设计友善的表单
    【转】从电子政务网络建设迈向政府数据中心建设
    (CF1394 A)Boboniu Chats with Du
    (CF1384B2)Koa and the Beach (Hard Version)
    牛客第十场自闭
    ORACLE 日期加减操作 xiao
    python 占位符
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11096283.html
Copyright © 2020-2023  润新知