Sunday, January 1, 2017

374. Guess Number Higher or Lower

Q:

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:
n = 10, I pick 6.

Return 6.

A:

没什么想的,就是取中间值,然后对比


/* 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) {
        return helper(1,n);
    }
    private int helper(int a, int b){
        if(a==b)
            return a;
        int mid = a + (b-a)/2;
        int res = guess(mid);
        if(res == 0)
            return mid;
        if(res == 1)
            return helper(mid+1,b);
        // res == 1, mine is bigger
        return helper(a,mid-1);
    }
}
 


Learned:

1:  guess(int num) return -1, mean my target number is lower than your given num这个是题意理解反了。
2:  求mid的时候,  以前还记得,刚刚忘了(主要是LC一直没考虑这种情况), 要写成
int mid = a + (b-a)/2;

No comments:

Post a Comment