278. First Bad Version

problem

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.

有n个版本,损坏的版本后面也会损坏,求第一个损坏的白本

solution

  • 问题抽象为在[1,1,1,1,0,0,0]的序列里寻找第一个0

使用简单二分查找(Time Limit Exceeded)

# 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
        """
        mid = (1+n)/2
        start = 1
        end = n
        if isBadVersion(1):
            return 1
        else:
            while start <= end:
                if isBadVersion(mid):
                    end = mid
                else:
                    start = mid
                mid = (start+end)/2
            return start

问题出在下标没有+1,-1

end = mid - 1
start = mid + 1
  • 某些语言中start+end可能超过最大int值
mid = start + (end - start)/2
优于
mid = (start + end)/2
posted @ 2016-11-21 10:42  Salmd  阅读(122)  评论(0)    收藏  举报