136.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.

我从1到n中选择一个数字。 你必须猜测我选择了哪个号码。

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):

您调用预定义的API guess(int num),它返回3个可能的结果(-1,1或0):

-1 : My number is lower
 1 : My number is higher
 0 : Congrats! You got it!

Example :

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

解答:

 1 /* The guess API is defined in the parent class GuessGame.
 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 public class Solution extends GuessGame {
 7     public int guessNumber(int n) {
 8         int i = 1, j = n;
 9         while(i < j) {
10             int mid = i + (j - i) / 2;
11             if(guess(mid) == 0) {
12                 return mid;
13             } else if(guess(mid) == 1) {
14                 i = mid + 1;
15             } else {
16                 j = mid;
17             }
18         }
19         return i;
20     }
21 }

详解:

二分搜索法

posted @ 2018-09-04 20:27  chan_ai_chao  阅读(106)  评论(0编辑  收藏  举报