374. 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'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 = 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 low=1,high=n,mid;
 9         while(low<=high){
10             mid=low+(high-low)/2;
11             if(guess(mid)==0)   return mid;
12             else if(guess(mid)==1) low=mid+1;
13             else    high=mid-1;
14         }
15         //任意返回值都能ac,不加的话leetcode编译的时候会报错
16         return 1;
17     }
18 }

 

 

 

posted @ 2018-10-16 00:15  杜王町上班族  阅读(116)  评论(0编辑  收藏  举报