374.Guess Number Higher or Lower

Solution 1: accepted 1ms

The most standard binary search.

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
public class Solution extends GuessGame {
public int guessNumber(int n) {
int lo = 1;
int hi = n;
while (lo + 1 < hi) {
int mid = lo + (hi - lo) / 2;
System.out.println(mid);
if (guess(mid) > 0) {
lo = mid;
} else if (guess(mid) < 0) {
hi = mid;
} else {
return mid;
}
}
if (guess(lo) == 0) {
return lo;
} else if (guess(hi) == 0) {
return hi;
} else {
return 0;
}
}
}