今天和大家聊的问题叫做 猜数字大小,我们先来看题面:https://leetcode-cn.com/problems/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 3 possible results:
-1: The number I picked is lower than your guess (i.e. pick < num).1: The number I picked is higher than your guess (i.e. pick > num).0: The number I picked is equal to your guess (i.e. pick == num).
Return the number that I picked.
猜数字游戏的规则如下:
每轮游戏,我都会从 1 到 n 随机选择一个数字。 请你猜选出的是哪个数字。如果你猜错了,我会告诉你,你猜测的数字比我选出的数字是大了还是小了。你可以通过调用一个预先定义好的接口 int guess(int num) 来获取猜测结果,返回值一共有 3 种可能的情况(-1,1 或 0):
-1:我选出的数字比你猜的数字小 pick < num1:我选出的数字比你猜的数字大 pick > num0:我选出的数字和你猜的数字一样。恭喜!你猜对了!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
解题
主要思路:在调用guess()方法时,返回结果这里题目描述的很不清楚,返回-1,是代表你猜的数字大了。同理,返回1,是代表你猜的数字小了。理解了这个,就可以很容易的想到使用二分查找了。要注意在求中间值的时候,注意使用 left + (right - left)/2 来防止溢出
public class Solution extends GuessGame { public int guessNumber(int n) { int left = 1; int right = n; while (left <= right){ int mid = left +(right - left)/2; if(guess(mid) == 1) left = mid+1; else if(guess(mid) == -1) right = mid - 1; else return mid; } return -1; } }
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。