|
|
|
|
|
|
|
|
|
|
|
# The isBadVersion API is already defined for you. |
|
|
|
|
|
# @param version, an integer |
|
|
|
|
|
# @return a bool |
|
|
|
|
|
# def isBadVersion(version): |
|
|
|
|
|
|
|
|
|
|
|
# I am assuming that the latest definitely is bad based on the way the problem is worded |
|
|
|
|
|
# so I will just implement a binary search pretty mcuh |
|
|
|
|
|
|
|
|
|
|
|
def isBadVersion(n): |
|
|
|
|
|
return n >= 4 |
|
|
|
|
|
|
|
|
|
|
|
class Solution: |
|
|
|
|
|
def firstBadVersion(self, n): |
|
|
|
|
|
# This check cuts out a case quickly, and also makes the logic easier to write |
|
|
|
|
|
# because negatives and zeros no longer have to be dealt with |
|
|
|
|
|
if isBadVersion(0): |
|
|
|
|
|
return 0 |
|
|
|
|
|
knownGood = 0 |
|
|
|
|
|
knownBad = n |
|
|
|
|
|
while knownBad - knownGood > 1: |
|
|
|
|
|
# find the mid point |
|
|
|
|
|
# check whether it's good or bad, and update accordingly |
|
|
|
|
|
mid = (knownGood + knownBad) // 2 |
|
|
|
|
|
if isBadVersion(mid): |
|
|
|
|
|
knownBad = mid |
|
|
|
|
|
else: |
|
|
|
|
|
knownGood = mid |
|
|
|
|
|
return knownBad |
|
|
|
|
|
|
|
|
|
|
|
s = Solution() |
|
|
|
|
|
print("Expected: 4") |
|
|
|
|
|
print("Got:", s.firstBadVersion(5)) |