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;
        }
    }
  • 相关阅读:
    【转载】 miniImageNet数据集介绍
    【转载】 聊聊统计学里的置信度和置信区间
    小样本学习(Few shot learning)标准数据集(miniImageNet、tieredImageNet、FewshotCIFAR100)下载地址
    配色素描必备书籍分享
    Jq滚动条插件写法(二)
    获得样式属性和外联样式
    windows7下gvim多标签打开新文件
    JQ插件jkscroll应用到页面中的效果
    《精通javascript》几个简单的函数(一)
    事件冒泡
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11096283.html
Copyright © 2011-2022 走看看