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 number that >= the target number
    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 number that >= the target number
    while (l < r) {
      final 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
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if num is higher than the picked number
#          1 if num is lower than the picked number
#          otherwise return 0
# def guess(num: int) -> int:

class Solution:
  def guessNumber(self, n: int) -> int:
    l = 1
    r = n

    # Find the first guess number that >= the target number
    while l < r:
      m = (l + r) // 2
      if guess(m) <= 0:  # -1, 0
        r = m
      else:
        l = m + 1

    return l