Leetcode/LeetCode75

[Binary Search][Easy] 374. Guess Number Higher or Lower

자전거통학 2024. 1. 9. 05:25

https://leetcode.com/problems/guess-number-higher-or-lower/description

 

Guess Number Higher or Lower - LeetCode

Can you solve this real interview question? Guess Number Higher or Lower - 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

leetcode.com

 

Q. 1-n까지의 수 중 하나를 찾는(pick value) 추측게임을 한다고 할때, 추측이 pick value보다 크면 -1, 같으면 0, 추측이 크면 1을 반환하는 함수를 가지고, 

답이 되는 pick value를 찾아 반환하라.   

 

A. 내가 추측값을 어떻게 지정하느냐가 핵심. 주로 중간 값을 취하면 binary rearch를 사용할 수 있겠다. 

 

 

int guessNumber_help(int left, int right)
{
    if(left > right) return -1;

    int mid = left + (right-left)/2;

    int retGuess = guess(mid);
    if(retGuess < 0)   return guessNumber_help(left, mid-1);
    if(retGuess == 1)  return guessNumber_help(mid+1, right);
    return mid;
}

int guessNumber(int n) {

    return guessNumber_help(1, n);
}