leetcode 374. Guess Number Higher or Lower 、375. Guess Number Higher or Lower II

374. Guess Number Higher or Lower

二分查找就好

// 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 start = 1, end = n;
        while(start < end){
            int mid = start + (end - start)/2;
            int res = guess(mid);
            if(res == 0)
                return mid;
            else if(res < 0)
                end = mid - 1;
            else
                start = mid + 1;       
        }
        return start;
    }
};

 

posted @ 2019-05-27 21:27  有梦就要去实现他  阅读(93)  评论(0编辑  收藏  举报