Problem
- Leetcode 374. Guess Number Higher or Lower - Binary Search
- Level: Easy
- Link
My Code
기본적인 Binary Search 문제이다. n = 2, pick = 2, n=1, pick 1 처럼 interval이 얼마 차이 나지 않는 경우들에 대한 조건처리가 잘 되어야 한다.
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
left = 1
right = n
while left < right:
mid = (left + right) // 2
if guess(mid) == -1:
right = mid - 1
elif guess(mid) == 1:
left = mid + 1
else:
return mid
return left
'개발공부 > algorithm' 카테고리의 다른 글
[Leetcode][python] 1528. Shuffle String (0) | 2021.07.04 |
---|---|
[Leetcode][python] 14. Longest Common Prefix (0) | 2021.07.04 |
[leetcode][python] 278. First Bad Version - Binary Search (0) | 2021.07.04 |
[Leetcode][python] 58: Length of Last Word (0) | 2021.06.24 |
[백준][python] 17626 - Four squares (0) | 2021.06.06 |