Leetcode 278 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.

 

假设序列为 PPPPFFFFFF,我们其实是想到找第一个F。所以这是一个典型的binary search寻找第一个>=target的问题。

 1 # The isBadVersion API is already defined for you.
 2 # @param version, an integer
 3 # @return a bool
 4 # def isBadVersion(version):
 5 
 6 class Solution(object):
 7     def firstBadVersion(self, n):
 8         """
 9         :type n: int
10         :rtype: int
11         """
12         left = 1
13         right = n
14         
15         while left < right:
16             mid = (left + right)/2
17             if isBadVersion(mid):
18                 right = mid
19             else:
20                 left = mid+1
21         
22         return left   

 

posted @ 2016-12-15 12:47  lettuan  阅读(155)  评论(0编辑  收藏  举报