Simple Python Solution Binary Search(both iterative and recursive versions)


  • 2
    Y

    Iterative version:

    def firstBadVersion(self, n):
            low = 1
            high = n
            while(low < high):
                mid = (low + high)/2
                if isBadVersion(mid) == True:
                    high = mid
                else:
                    low = mid + 1
            return high
    

    Recursive version:

        def firstBadVersion(self, n):
            return self.binarySearch(1, n)
        
        def binarySearch(self, low, high):
            if low == high:
                return low
            mid = (low + high)/2
            if isBadVersion(mid) == True:
                return self.binarySearch(low, mid)
            else:
                return self.binarySearch(mid + 1, high)

Log in to reply
 

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