博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
374. Guess Number Higher or Lower
阅读量:4637 次
发布时间:2019-06-09

本文共 1136 字,大约阅读时间需要 3 分钟。

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 = 6Output: 6

 

Approach #1:

// Forward declaration of guess API.// @param num, your guess// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0int guess(int num);class Solution {public:    int guessNumber(int n) {        int l = 1, r = n;        while (l <= r) {            int m = l + (r - l) / 2;            //cout << m << endl;            if (guess(m) == 1) l = m + 1;            else if (guess(m) == -1) r = m - 1;            else return m;        }        return -1;    }};

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Guess Number Higher or Lower.

 

Analysis:

you should pay attention to that My number is lower  represent pick > m.

 

转载于:https://www.cnblogs.com/ruruozhenhao/p/9907465.html

你可能感兴趣的文章
儿子和女儿——解释器和编译器的区别与联系
查看>>
第一阶段冲刺3
查看>>
父类引用指向子类对象
查看>>
网页如何实现下载功能
查看>>
IT男专用表白程序
查看>>
读《大道至简》第六章感想
查看>>
ef linq 中判断实体中是否包含某集合
查看>>
章三 链表
查看>>
Solution for Concurrent number of AOS' for this application exceeds the licensed number
查看>>
CSE 3100 Systems Programming
查看>>
IntelliJ IDEA 的Project structure说明
查看>>
Java Security(JCE基本概念)
查看>>
Linux Supervisor的安装与使用入门
查看>>
创建 PSO
查看>>
JasperReport报表设计4
查看>>
项目活动定义 概述
查看>>
团队冲刺04
查看>>
我的Python分析成长之路8
查看>>
泛型在三层中的应用
查看>>
SharePoint2010 -- 管理配置文件同步
查看>>