스터디/코테
[LeetCode] 374 | Guess Number Higher or Lower | Python
yun_s
2022. 11. 16. 09:25
728x90
반응형
문제 링크: https://leetcode.com/problems/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.
조건
- 1 <= n <=$2^{31}-1$
- 1 <= pick <= n
내 풀이
Binary Search(이분탐색)으로 푼다.
코드
# The guess API is already defined for you.
# @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
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
left = 1
right = n+1
while left+1 < right:
mid = (left + right) // 2
if guess(mid) >= 0:
left = mid
else:
right = mid
return left
728x90
반응형