Python solution with detailed explanation


  • 0
    G

    Solution

    Guess Number Higher or Lower https://leetcode.com/problems/guess-number-higher-or-lower/

    Binary Search

    • low to high is 1 to N. Apply standard binary search.
    class Solution(object):
        def guessNumber(self, n):
            """
            :type n: int
            :rtype: int
            """
            low = 1
            high = n
            while low <= high:
                mid = low + (high-low)//2
                ans = guess(mid)
                if ans == 0:
                    return mid
                elif ans == -1:
                    high = mid - 1
                else:
                    low = mid + 1
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.