Leetcode - Guess Number Higher or Lower

My code:

/* The guess API is defined in the parent class GuessGame.
   @param num, your guess
   @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
      int guess(int num); */

public class Solution extends GuessGame {
    public int guessNumber(int n) {
        int begin = 1;
        int end = n;
        while (begin <= end) {
            int mid = begin + (end - begin) / 2;
            if (guess(mid) < 0) {
                end = mid - 1;
            }
            else if (guess(mid) > 0) {
                begin = mid + 1;
            }
            else {
                return mid;
            }
        }
        return -1;
    }
}

简单题。

可以看下他给的一篇文章,介绍了一个新的search
叫做: Ternary Search

reference:
https://leetcode.com/articles/guess-number-higher-or-lower/#approach-3-ternary-search-accepted

Anyway, Good luck, Richardo! — 09/21/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/a066436ae51d#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞