[LeetCode] 374. Guess Number Higher or Lower 猜数字大小

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.

从1到n中,我随便选一个数字,然后你来猜。有一个函数可以返回我选的数比你猜的数大还是小或者相等,分别用1,-1,0来表示。最后要返回我选的这个数。注意:"My number"  指的是我选的那个数,不是你猜的数。

解法:二分搜索法

Java:

public int guessNumber(int n) {
    int i = 1, j = n;
    while(i < j) {
        int mid = i + (j - i) / 2;
        if(guess(mid) == 0) {
            return mid;
        } else if(guess(mid) == 1) {
            i = mid + 1;
        } else {
            j = mid;
        }
    }
    return i;
}  

Python:

class Solution(object):
    def guessNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        low = 1
        high = n
        while low <= high:
            mid = (low + high)//2
            res =  guess(mid)
            if res == 0 :
                return mid
            elif res == -1:
                high = mid - 1
            else:
                low = mid + 1  

Python:

class Solution(object):
    def guessNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        left, right = 1, n
        while left <= right:
            mid = left + (right - left) / 2
            if guess(mid) <= 0:
                right = mid - 1
            else:
                left = mid + 1
        return left  

C++:

// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);

class Solution {
public:
    int guessNumber(int n) {
        if (guess(n) == 0) return n;
        int left = 1, right = n;
        while (left < right) {
            int mid = left + (right - left) / 2, t = guess(mid);
            if (t == 0) return mid;
            else if (t == 1) left = mid;
            else right = mid;
        }
        return left;
    }
};

  

类似题目:

[LeetCode] 375. Guess Number Higher or Lower II 猜数字大小 II

 

All LeetCode Questions List 题目汇总

 

 

 

posted @ 2018-03-24 06:47  轻风舞动  阅读(599)  评论(0编辑  收藏  举报