LeetCode 374. Guess Number Higher or Lower

Guess Number Higher or Lower

unlocked question, 不贴截图了

EST 7/13/2016, 1:14AM. Beijing time 7/13/2016, 1:14PM. 截至目前Leetcode最新的一道题 I’m loling, 这还是我第一次做刚刚发出来的题
现在题越来越多,大量重复题,这道题是很典型的binary search
用leetcode给出的函数: int guess(int num)判断现在的数字是大了还是小了,binary search小了就往右,大了就往左

// 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) {
        int low(0), high(n);
        while (low <= high) {
            int mid = low + (high - low) / 2;
            int d = guess(mid);
            if (d == 0) return mid;
            else if (d == 1) low = mid + 1;
            else high = mid - 1;
        }
        return high;
    }
};
    原文作者:Terence_F
    原文地址: https://www.jianshu.com/p/18bc5b6ea2c1
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞