374. Guess Number Higher or Lower

。。。。

一开始算了几次TLE。。

三刷发现自己不会二分了。 最后还是套用了YES LEFT NO RIGHT做的。。

/* 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 l = 1;
        int r = n;
        
        while (l <= r) {
            int m = l + (r - l) / 2;
            int ans = guess(m);
            if (ans <= 0) r = m - 1;
            else l = m + 1;
        }
        
        return l;
    }
}
posted @ 2016-11-05 11:35  哇呀呀..生气啦~  阅读(86)  评论(0)    收藏  举报