关闭

【Leetcode】374. Guess Number Higher or Lower【二分搜索】

标签: leetcode二分
56人阅读 评论(0) 收藏 举报
分类:

374. Guess Number Higher or Lower

  • Total Accepted: 17904
  • Total Submissions: 56954
  • Difficulty: 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.


思路:二分法


代码1:

public class Solution extends GuessGame {
    public int guessNumber(int n) {
        int begin = 1, end = n, mid;
        while(begin <= end){
            mid = begin + (end - begin)/2;
            int flag = guess(mid);
            if(flag == 0) return mid;
            if(flag < 0) end = mid - 1;
            else begin = mid + 1;
        }
        return begin;
    }
}
代码2:http://blog.csdn.net/corpsepiges/article/details/51898386

public class Solution extends GuessGame {  
    public int guessNumber(int n) {  
        return guessRange(1,n);  
    }  
    public int guessRange(int start,int end){  
        if(start==end){  
            return start;  
        }  
        int middle=start/2+end/2+(start%2+end%2)/2;  
        int ans=guess(middle);  
        if(ans==0){  
            return middle;  
        }  
        if(ans>0){  
            return guessRange(middle+1,end);  
        }  
        return guessRange(start,middle-1);  
    }  
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:42099次
    • 积分:1202
    • 等级:
    • 排名:千里之外
    • 原创:65篇
    • 转载:101篇
    • 译文:1篇
    • 评论:4条
    文章分类