374. Guess Number Higher or Lower
Problem
A number was picked from 1…n. The provided API guess(num) returns −1 if the pick is lower than num, 1 if it is higher, and 0 if it's correct. Return the picked number.
Example: n = 10, pick = 6 → 6
Constraints: n ≤ 2³¹ − 1.
Classic binary search where the comparison is the provided guess(num) API: -1 means the pick is lower than num, 1 higher, 0 found.
Complexity: O(log n) calls.
class Solution:
def guessNumber(self, n: int) -> int:
lo, hi = 1, n
while True:
mid = (lo + hi) // 2
g = guess(mid) # provided by LeetCode
if g == 0:
return mid
if g < 0:
hi = mid - 1
else:
lo = mid + 1
for n, PICK in ((10, 6), (1, 1), (2, 1), (2, 2), (2126753390, 1702766719)):
def guess(num, pick=PICK):
return 0 if num == pick else (-1 if pick < num else 1)
assert Solution().guessNumber(n) == PICK
class GuessGame { // provided by LeetCode
static int pick;
int guess(int num) { return Integer.compare(pick, num); }
}
class Solution extends GuessGame {
public int guessNumber(int n) {
int lo = 1, hi = n;
while (true) {
int mid = lo + (hi - lo) / 2; // avoids int overflow
int g = guess(mid);
if (g == 0) return mid;
if (g < 0) hi = mid - 1; else lo = mid + 1;
}
}
}
var pick int // provided by LeetCode (the tests set it)
func guess(num int) int { // provided by LeetCode
if num == pick {
return 0
}
if pick < num {
return -1
}
return 1
}
func guessNumber(n int) int {
lo, hi := 1, n
for {
mid := lo + (hi-lo)/2
switch guess(mid) {
case 0:
return mid
case -1:
hi = mid - 1
default:
lo = mid + 1
}
}
}