Sponsored
Sponsored
This approach uses binary search to guess the number. We maintain two pointers, low
and high
, representing the current range of numbers we need to search. Then, we guess the middle number of the range and adjust our range based on the response from the guess
API. If the guessed number is correct, we return it. Otherwise, we adjust the low
or high
pointers and repeat the process until the number is guessed correctly.
Time Complexity: O(log n)
Space Complexity: O(1)
1public class Solution {
2 public int guessNumber(int n) {
3 int low = 1, high = n;
4 while (low <= high) {
5 int mid = low + (high - low) / 2;
6 int res = guess(mid);
7 if (res == 0)
8 return mid;
9 else if (res < 0)
10 high = mid - 1;
11 else
12 low = mid + 1;
13 }
14 return -1; // should not reach here
15 }
16}
In this Java implementation, binary search is performed to guess the number. The guess
function is pre-defined and returns whether the current guess needs to be adjusted up or down.
This approach is a straightforward linear search that iterates from 1
to n
guessing each number one by one until it finds the correct pick. It's simple but not efficient for larger values of n
and is provided here primarily for educational purposes.
Time Complexity: O(n)
Space Complexity: O(1)
1
In Java, this approach iterates over each number starting from 1
until the correct number is guessed, which is the easiest and most intuitive approach.