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.

基本二分查找

class Solution(object):
    def firstBadVersion(self, n):
        a, b,ans = 1, n, 1
        while a <= b:
            x = a + (b-a)/2
            if isBadVersion(x):
                ans = x
                b = x-1
            else:
                a = x+1
        return ans

 

posted @ 2016-05-13 17:53  lilixu  阅读(91)  评论(0编辑  收藏  举报