lintcode Guess Number Game(Java)

1.题目

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-100,取数字20,每次猜一个(提供了API guess(int num)),等于20,返回0,大于20返回-1,小于20返回1,直到返回0为止。

样例
n = 10, I pick 4 (but you don’t know)
Return 4. Correct !

2.解法

其实就是二分法解题,关键的一步就是计算中间节点。
int middle = (start + end)/2,有可能导致溢出,下面的方法更好
int middle = start + (end - start)/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 {
    /**
     * @param n an integer
     * @return the number you guess
     */
    public int guessNumber(int n) {
        // Write your code here
         int start = 0;
        int end = n;

        while (start < end){
            int middle = start + (end - start)/2;//中间节点的算法
            int result = guess(middle);
            if (result == -1){
                end = middle - 1;
            }else if (result == 1){
                start = middle + 1;
            }else if (result == 0){
                return middle;
            }
        }
           return start;
    }
}

你可能感兴趣的:(算法)