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}
The C# solution leverages binary search. It's a direct implementation where we incrementally adjust guesses based on the feedback from the guess
API, looking for the correct number.
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.