[C++] 374. Guess Number Higher or Lower

정지은·2022년 11월 16일
0

코딩문제

목록 보기
16/25

374. 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 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.

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

접근

#이진탐색

숫자의 대소를 구분하는 함수는 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.

profile
Steady!

0개의 댓글