Skip to content

374. Guess Number Higher or Lower 👍

  • Time: $O(\log n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * Forward declaration of guess API.
 * (The problem description is not clear, so I translate it into follows.)
 *
 * @param traget num
 *        guess num
 *
 * @return -1 if guess num >  target num
 *          0 if guess num == target num
 *          1 if guess num <  target num
 */

class Solution {
 public:
  int guessNumber(int n) {
    int l = 1;
    int r = n;

    // find the first guess num that >= target num
    while (l < r) {
      const int m = l + (r - l) / 2;
      if (guess(m) <= 0)  // -1, 0
        r = m;
      else
        l = m + 1;
    }

    return l;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * Forward declaration of guess API.
 * (The problem description is not clear, so I translate it into follows.)
 *
 * @param traget num
 *        guess num
 *
 * @return -1 if guess num >  target num
 *          0 if guess num == target num
 *          1 if guess num <  target num
 */

public class Solution extends GuessGame {
  public int guessNumber(int n) {
    int l = 1;
    int r = n;

    // find the first guess num that >= target num
    while (l < r) {
      final int m = l + (r - l) / 2;
      if (guess(m) <= 0) // -1, 0
        r = m;
      else
        l = m + 1;
    }

    return l;
  }
}