본문 바로가기
Leetcode

[LeetCode] Guess Number Higher or Lower 파이썬 (binary search)

by YGSEO 2021. 4. 14.
728x90

while 문으로 해결하려 했더니 시간초과

 

Binary Search로 풀어야 함.

 

# 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, right = 1, n
        while left <= right:
            mid = (right + left) // 2
            if guess(mid) <= 0: # noqa
                right = mid - 1
            else:
                left = mid + 1
        return left

 

728x90

댓글