- First Bad Version
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
my thoughts:
1. typical binary search
my solution:
**********32ms
# 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
"""
l = 1
r = n
while True:
if l == r:
return l
if isBadVersion((l+r)/2) and not isBadVersion((l+r)/2-1):
return (l+r)/2
elif not isBadVersion((l+r)/2) and isBadVersion((l+r)/2+1):
return (l+r)/2+1
elif isBadVersion((l+r)/2):
r = (l+r)/2
elif not isBadVersion((l+r)/2):
l = (l+r)/2
my comments:
from other ppl's solution:
1. bit operation is faster than /2, just keep left pointer always good if it is good from beginning, keep right pointer always bad, 22ms:
class Solution(object):
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
i = 1
j = n
while i < j:
index = i + ((j - i) >> 1)
if isBadVersion(index):
j = index - 1
else:
i = index + 1
if isBadVersion(i):
return i
else:
return i + 1