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
    题目很明显的二分查找,有序数列,找固定数字
     1 /* The guess API is defined in the parent class GuessGame.
     2    @param num, your guess
     3    @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
     4       int guess(int num); */
     5 
     6 public class Solution extends GuessGame {
     7     public int guessNumber(int n) {
     8         int low=1,high=n,mid;
     9         while(low<=high){
    10             mid=low+(high-low)/2;
    11             if(guess(mid)==0)   return mid;
    12             else if(guess(mid)==1) low=mid+1;
    13             else    high=mid-1;
    14         }
    15         //任意返回值都能ac,不加的话leetcode编译的时候会报错
    16         return 1;
    17     }
    18 }
  • 相关阅读:
    Nodejs-原型链污染
    dpwwn-02靶机渗透
    dpwwn-01靶机渗透
    Bulldog1靶机渗透
    php+html实现用户登录退出
    DC4靶机
    vulnhub-Os-hackNos-3
    Linux系统解析XML中文乱问题
    idea添加database
    PL/SQL学习笔记
  • 原文地址:https://www.cnblogs.com/real1587/p/9795583.html
Copyright © 2011-2022 走看看