LeetCode75-374-Guess-Number

🧠 Summary of Thoughts

  • Binary Search
  • Update low and high to mid + 1 or mid - 1
  • mid = low + (high - low) / 2
  • return -1

✅ Code(Java)

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
/** 
* Forward declaration of guess API.
* @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
* int guess(int num);
*/

public class Solution extends GuessGame {
public int guessNumber(int n) {
int low = 1;
int high = n;
int mid = 0;
while (low <= high) {
mid = low + (high - low) / 2;
if (guess(mid) == -1) {
high = mid - 1;
} else if (guess(mid) == 1) {
low = mid + 1;
} else {
return mid;
}
}
return -1;
}
}

LeetCode75-374-Guess-Number
https://powersixxx.github.io/leetcode-blog/2026/04/09/LeetCode75-374-Guess-Number/
作者
Baowen Liu
发布于
2026年4月9日
许可协议