Leetcode 374. Guess Number Higher or Lower

来源:互联网 发布:js里取juid 编辑:程序博客网 时间:2024/05/13 19:28

Note that the param for guess() is the number you need to guess.

e.g. 

guess(5) = 1 when the number you need to guess is 6. 

/** * We can easily figure out a O(n) solution which calls guess() from 1 to k,  * k is the number we want to return. * An efiicient solution is using binary search.  */ public class Solution extends GuessGame {    public int guessNumber(int n) {        int low = 1, high = n, mid = 0;        while (low + 1 < high) {            mid = low + (high - low) / 2;            if (guess(mid) == 0) return mid;            else if (guess(mid) == 1) low = mid;            else high = mid;        }        return guess(low) == 0 ? low : high;    }}


0 0
原创粉丝点击