Binary Search Python Code


  • 1
    R
    # The isBadVersion API is already defined for you.
    # @param version, an integer
    # @return a bool
    # def isBadVersion(version):
    
    class Solution(object):
        def firstBadVersion(self, n):
            """
            :type n: int
            :rtype: int
            """
            def test(n):
                if isBadVersion(n):
                    if( not isBadVersion(n-1) or n == 1):
                        return 0
                    else:
                        return 1
                else:
                    return -1
                    
            def binSearch(start, end):
                mid = 0.5* (start+end)
                if not test(mid):
                    return mid
                if test(mid) == 1:
                    return binSearch(start,mid)
                if test(mid) == -1:
                    return binSearch(mid,end)
            
            return int(binSearch(0,n))
                      
    

Log in to reply
 

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