• 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;
        }
    }
  • 相关阅读:
    iOS项目中常见的文件
    RN 导入原有Xcode项目中,引入Pod依赖出现的问题与解决
    Xcode中StoryBoard Reference 新特性的使用
    非等高cell实战(01)-- 实现微博页面
    iOS回顾笔记(09) -- Cell的添加、删除、更新、批量操作
    iOS回顾笔记(08) -- 自定义Cell的类型和创建步骤总结
    unittest中的测试固件
    unittest测试用例的执行顺序
    unittest各个组件之间的关系
    ubuntu16.04开机时的.local问题
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11096283.html
Copyright © 2020-2023  润新知