374:猜数字大小

This commit is contained in:
huangge1199@hotmail.com 2021-06-14 21:39:23 +08:00
parent 0f6fb4830f
commit 8de15a737f
3 changed files with 165 additions and 1 deletions

View File

@ -0,0 +1,108 @@
//猜数字游戏的规则如下
//
//
// 每轮游戏我都会从 1 n 随机选择一个数字 请你猜选出的是哪个数字
// 如果你猜错了我会告诉你你猜测的数字比我选出的数字是大了还是小了
//
//
// 你可以通过调用一个预先定义好的接口 int guess(int num) 来获取猜测结果返回值一共有 3 种可能的情况-11 0
//
//
// -1我选出的数字比你猜的数字小 pick < num
// 1我选出的数字比你猜的数字大 pick > num
// 0我选出的数字和你猜的数字一样恭喜你猜对了pick == num
//
//
// 返回我选出的数字
//
//
//
// 示例 1
//
//
//输入n = 10, pick = 6
//输出6
//
//
// 示例 2
//
//
//输入n = 1, pick = 1
//输出1
//
//
// 示例 3
//
//
//输入n = 2, pick = 1
//输出1
//
//
// 示例 4
//
//
//输入n = 2, pick = 2
//输出2
//
//
//
//
// 提示
//
//
// 1 <= n <= 231 - 1
// 1 <= pick <= n
//
// Related Topics 二分查找
// 👍 148 👎 0
package leetcode.editor.cn;
//374:猜数字大小
class GuessNumberHigherOrLower {
public static void main(String[] args) {
//测试代码
Solution solution = new GuessNumberHigherOrLower().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Forward declaration of guess API.
*
* @param num your guess
* @return -1 if num is lower than the guess number
* 1 if num is higher than the guess number
* otherwise return 0
* int guess(int num);
*/
public class Solution extends GuessGame {
public int guessNumber(int n) {
int start = 1;
int end = n;
while (start < end) {
int num = start + (end - start) / 2;
int result = guess(num);
if (result == 0) {
return num;
}
if (result == -1) {
end = num - 1;
} else {
start = num + 1;
}
}
return start;
}
int guess(int num) {
return 0;
}
}
private class GuessGame {
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,56 @@
<p>猜数字游戏的规则如下:</p>
<ul>
<li>每轮游戏,我都会从 <strong>1</strong> 到 <em><strong>n</strong></em> 随机选择一个数字。 请你猜选出的是哪个数字。</li>
<li>如果你猜错了,我会告诉你,你猜测的数字比我选出的数字是大了还是小了。</li>
</ul>
<p>你可以通过调用一个预先定义好的接口 <code>int guess(int num)</code> 来获取猜测结果,返回值一共有 3 种可能的情况(<code>-1</code><code>1</code> 或 <code>0</code></p>
<ul>
<li>-1我选出的数字比你猜的数字小 <code>pick < num</code></li>
<li>1我选出的数字比你猜的数字大 <code>pick > num</code></li>
<li>0我选出的数字和你猜的数字一样。恭喜你猜对了<code>pick == num</code></li>
</ul>
<p>返回我选出的数字。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>n = 10, pick = 6
<strong>输出:</strong>6
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>n = 1, pick = 1
<strong>输出:</strong>1
</pre>
<p><strong>示例 3</strong></p>
<pre>
<strong>输入:</strong>n = 2, pick = 1
<strong>输出:</strong>1
</pre>
<p><strong>示例 4</strong></p>
<pre>
<strong>输入:</strong>n = 2, pick = 2
<strong>输出:</strong>2
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= n <= 2<sup>31</sup> - 1</code></li>
<li><code>1 <= pick <= n</code></li>
</ul>
<div><div>Related Topics</div><div><li>二分查找</li></div></div>\n<div><li>👍 148</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long