We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API int guess(int num), which returns three possible results:
-1: Your guess is higher than the number I picked (i.e. num > pick).
1: Your guess is lower than the number I picked (i.e. num < pick).
0: your guess is equal to the number I picked (i.e. num == pick).
Return the number that I picked.
#이진탐색
숫자의 대소를 구분하는 함수는 guess(n)으로 이미 주어져 있으므로, pick값만 찾아내면 된다.
하지만 완전탐색을 하면 시간초과가 발생하므로, 이진탐색을 통해 탐색 시간을 줄여야 한다.
mid의 값이 integer 범위에서는 오버플로우를 일으키므로, (right+left)/2 대신 left+(right-left)/2를 사용했다.
/**
* 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);
*/
class Solution {
public:
int guessNumber(int n) {
int left = 1;
int right = n;
while(left<=right) {
int mid = left + (right - left) / 2;
if(!guess(mid)) {
return mid;
}
if(guess(mid)<0){
right = mid-1;
} else {
left = mid+1;
}
}
return -1;
}
};
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Guess Number Higher or Lower.
Memory Usage: 6 MB, less than 22.94% of C++ online submissions for Guess Number Higher or Lower.