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;
        }
    }
  • 相关阅读:
    如何启用EMGrid/Cloud Control的HTTP而非HTTPS协议登陆
    Oracle Enterprise Manager 12c 新特性:实时RealTime Addm
    php 面向对象三大特征
    C++ 运算符重载
    C++面向对象_复制构造函数+构造函数+析构函数+static+友元
    位运算符和位运算
    SqlHelper.class.php
    C++ 流
    C++ 虚函数与多态
    C++ 继承与派生
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11096283.html
Copyright © 2011-2022 走看看