zoukankan      html  css  js  c++  java
  • Leetcode 374. Guess Number Higher or Lower

    374. Guess Number Higher or Lower

    • Total Accepted: 7396
    • Total Submissions: 23391
    • Difficulty: Easy

    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:

    n = 10, I pick 6.
    
    Return 6.

    思路:二分查找。这里的二分查找模板可以推广。下面有2个模板,注意各自的应用场景。

    代码:

    这个是在左闭右闭区间[low,high]中查找元素值>=查找值的第1个元素的位置,这里也考虑high位置和查找值的大小。

     1 // Forward declaration of guess API.
     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 class Solution {
     7 public:
     8     int guessNumber(int n) {
     9         int low=1,high=n,mid;
    10         while(low<=high){
    11             mid=low+(high-low)/2;
    12             if(guess(mid)==1){
    13                 low=mid+1;
    14             }
    15             else{
    16                 high=mid-1;
    17             }
    18         }
    19         return low;
    20     }
    21 };

    这个是在左闭右开区间[low,high)中查找元素值>=查找值的第1个元素的位置,这里不考虑high位置和查找值的大小。相当于STL的函数lower_bound()。

    本题有些特殊,就算high所在位置不被比较,如果排查了high之前所有位置和查找值的大小,最后low和high都停留在同1个位置,这时high虽然不被比较,但肯定就是high位置元素==查找值。例如在[1,2,3]中查找3。

     1 // Forward declaration of guess API.
     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 class Solution {
     7 public:
     8     int guessNumber(int n) {
     9         int low=1,high=n,mid;
    10         while(low<high){
    11             mid=low+(high-low)/2;
    12             if(guess(mid)==1){
    13                 low=mid+1;
    14             }
    15             else{
    16                 high=mid;
    17             }
    18         }
    19         return low;
    20     }
    21 };
  • 相关阅读:
    layui 参照赋值的两种方式
    c笔记
    Linux操作系统笔记
    make笔记
    Gcc如何知道文件类型。
    #include <xxx.h>和#include "xxx.h"的区别
    GCC编译流程
    c++ Socket客户端和服务端示例版本三(多线程版本)
    c++ Socket客户端和服务端示例版本二
    c++ Socket客户端和服务端示例版本一
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5691859.html
Copyright © 2011-2022 走看看