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)
1class Solution {
2public:
3 int guessNumber(int n) {
4 int low = 1, high = n;
5 while (low <= high) {
6 int mid = low + (high - low) / 2;
7 int res = guess(mid);
8 if (res == 0)
9 return mid;
10 else if (res < 0)
11 high = mid - 1;
12 else
13 low = mid + 1;
14 }
15 return -1; // should not reach here
16 }
17};
This C++ code implements binary search in a similar manner to C. The difference is syntax changes specific to C++. The guess
function is assumed to be defined elsewhere.
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
This C code implements a linear search. It simply checks each number in sequence until it finds the correct one using the guess
API.