개발공부/algorithm
[Leetcode][python] 374. Guess Number Higher or Lower - Binary Search
so.py
2021. 7. 4. 21:04
Problem
- Leetcode 374. Guess Number Higher or Lower - Binary Search
- Level: Easy
- Link
Guess Number Higher or Lower - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
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