반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 374 | Guess Number Higher or Lower | Python 본문
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
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 1926 | Nearest Exit from Entrance in Maze | Python (0) | 2022.11.21 |
---|---|
[LeetCode] 223 | Rectangle Area | Python (0) | 2022.11.17 |
[LeetCode] 947 | Most Stones Removed with Same Row or Column | Python (0) | 2022.11.14 |
[LeetCode] 1047 | Remove All Adjacent Duplicates In String | Python (0) | 2022.11.10 |
[LeetCode] 901 | Online Stock Span | Python (0) | 2022.11.09 |
Comments