1. 程式人生 > >Leetcode374. Guess Number Higher or Lower

Leetcode374. Guess Number Higher or Lower

@小花

還是一道easy難度的題目,直接放題目好了。

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 (-1

1, or 0):

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

Example:

n = 10, I pick 6.

Return 6.

這道題目就是個簡單的二分查詢的題目,要說的就兩點吧,第一,就是API返回的1是表示真實值比猜的值要大,不要搞反了。第二個,就是取中值的時候注意防止溢位。不要寫mid=(higher+lower)/2,而是按照下面程式中的寫法就行了。

/* The guess API is defined in the parent class GuessGame.
   @param num, your guess
   @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
      int guess(int num); */

public class Solution extends GuessGame {
     public int guessNumber(int n) {                      
     int lower = 1, higher = n; //1 10                
     while(lower <= higher){                                     
         int mid = lower + (higher - lower)/2;        
         int real_result = guess(mid);//-1 1          
         if(real_result == 0)                           
             return mid;                              
         else if(real_result == 1)                   
         {                                            
             lower = mid + 1;            
         }                                            
         else{                                        
             higher = mid - 1;
         }                                            
     }
     return -1;
                                                      
 }                                                    
}