[LeetCode]374. Guess Number Higher or Lower

来源:互联网 发布:海绵宝宝软件 编辑:程序博客网 时间:2024/06/05 02:19

题目描述: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.

题目重述:从1~n中选一个数让你猜,当小了返回-1,大了返回1,正好返回0。

解题思路:二分法递归查找

public class Solution extends GuessGame {    public int guessNumber(int n) {        //二分查找法        return helper(1,n);    }    public int helper(int start,int end){        //当首尾相等时,返回第一个元素        if(start==end)return start;        int mid=0;        //获取中间数        //Returns the value of the long argument; throwing an exception if the value overflows an int.        mid=Math.toIntExact(((long)start+(long)end)/2);        int r=0;        if(guess(mid)==0)r=mid;        //当返回1时表示该数更大,则在右半边递归查找        else if(guess(mid)==1) r=helper(mid+1,end);        //当返回-1时表示该数更小,则在左半边递归查找        else if(guess(mid)==-1) r=helper(start,mid-1);        return r;    }}