Skip to content

Latest commit

 

History

History
49 lines (35 loc) · 1.5 KB

File metadata and controls

49 lines (35 loc) · 1.5 KB

🐐 LeetCode 374. Guess Number Higher or Lower

  • Date : 2022.01.02(일)
  • Time : 25분

Problem

  • 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 3 possible results:

    • -1: The number I picked is lower than your guess (i.e. pick < num).
    • 1: The number I picked is higher than your guess (i.e. pick > num).
    • 0: The number I picked is equal to your guess (i.e. pick == num).
  • Return the number that I picked.

Constraints

  • 1 <= n <= 2&31 - 1
  • 1 <= pick <= n

Example

  • Input: n = 10, pick = 6
  • Output: 6



풀이

    def guessNumber(self, n: int) -> int:
        
        low = 1
        high = n

        while low <= high:

            mid = (low + high) >> 1
            value = guess(mid)

            if value == -1:
                high = mid - 1
            elif value == 1:
                low = mid + 1
            else: return mid

: n을 기준으로 pick을 찾아내는 문제이다. 역시 이진탐색으로 문제를 풀어보았다. 먼저 중간값을 넣어서 guess의 값을 출력해본다. 이 값이 -1이라면 너무 큰 값이므로 값을 빼준다. 만약 1이라면 작은 값이라는 뜻이므로 값을 더해준다. 이렇게 중간값을 바꿔가면서 계속 비교해주는 문제였다.