zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    工业设计之美
    狠挖用户需求与用户分析——赫志中
    《必然》
    在一周内学会使用 AUTO CAD
    可控硅调光知识总结
    PADS Logic Decal、Layout Decal绘制
    BUCK-BOOST反激变压器设计
    RCC BUCK-BOOST变压器设计
    产品生产
    由《旧制度与大革命》提取的5个感触
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11096283.html
Copyright © 2011-2022 走看看