当前位置: 首页 > news >正文

LeetCode374. 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 will tell you whether the number I picked is higher or lower than your guess.

You call a pre-defined API int guess(int num), which returns three possible results:

-1: Your guess is higher than the number I picked (i.e. num > pick).
1: Your guess is lower than the number I picked (i.e. num < pick).
0: your guess is equal to the number I picked (i.e. num == pick).
Return the number that I picked.

Example 1:

Input: n = 10, pick = 6
Output: 6
Example 2:

Input: n = 1, pick = 1
Output: 1
Example 3:

Input: n = 2, pick = 1
Output: 1

Constraints:

1 <= n <= 231 - 1
1 <= pick <= n

二、题解

/** * Forward declaration of guess API.* @param  num   your guess* @return 	     -1 if num is higher than the picked number*			      1 if num is lower than the picked number*               otherwise return 0* int guess(int num);*/class Solution {
public:int guessNumber(int n) {int l = 1,r = n;while(l <= r){int mid = l + ((r - l) >> 1);if(guess(mid) == 0) return mid;else if(guess(mid) == 1) l = mid + 1;else r = mid - 1;}return 0;}
};
http://www.lryc.cn/news/298145.html

相关文章:

  • 继承
  • 北斗卫星在物联网时代的应用探索
  • SQL注入 - 利用报错函数 floor 带回回显
  • NLP_Bag-Of-Words(词袋模型)
  • C语言rand随机数知识解析和猜数字小游戏
  • django中的缓存功能
  • 三、搜索与图论
  • 【翻译】Processing安卓模式的安装使用及打包发布(内含中文版截图)
  • MATLAB图像处理——边缘检测及图像分割算法
  • 探索设计模式:原型模式深入解析
  • IAR报错解决:Fatal Error[Pe1696]: cannot open source file “zcl_ha.h“
  • Qt网络编程-ZMQ的使用
  • 如何清理Docker占用的磁盘空间?
  • 从零开始学HCIA之NAT基本工作原理
  • Day40- 动态规划part08
  • 论文笔记:相似感知的多模态假新闻检测
  • 5G技术对物联网的影响
  • Nacos1.X源码解读(待完善)
  • 算法之双指针系列1
  • 苍穹外卖面试题
  • 【Qt 学习之路】在 Qt 使用 ZeroMQ
  • CI/CD到底是啥?持续集成/持续部署概念解释
  • golang常用库之-disintegration/imaging图片操作(生成缩略图)
  • CSS 控制 video 标签的控制栏组件的显隐
  • 数据可视化之维恩图 Venn diagram
  • 2024刘谦春晚第二个扑克牌魔术
  • 【k8s系列】(202402) 证书apiserver_client_certificate_expiration_seconds
  • Rust变量与常量介绍
  • Flask基础学习2
  • 文章页的上下篇功能是否有必要?boke112百科取消上下篇功能