Binary Search
public class Solution extends GuessGame {
public int guessNumber(int n) {
int start = 1;
int end = n;
// start end
while (start < end) {
int mid = start + (end - start) / 2;
int result = guess(mid);
if (result == -1) {
end = mid - 1;
} else if (result == 1) {
start = mid + 1;
} else {
return mid;
}
}
return start;
}
}
No comments:
Post a Comment