20170314-leetcode-278-First Bad Version

来源:互联网 发布:58端口使用技巧 编辑:程序博客网 时间:2024/05/18 02:32

1.Description

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,表示有n个这样的产品,找出第一个bad version,怎么判断bad,有自定义的函数,可以考虑使用二分查找的方式

2.Solution

# The isBadVersion API is already defined for you.# @param version, an integer# @return a bool# def isBadVersion(version):#Time:O(log n)#Method:Search the solution spaceclass Solution(object):    def firstBadVersion(self, n):        """        :type n: int        :rtype: int        """        left,right=1,n        while right>left and right-left!=1:            mid=(right+left)/2            if isBadVersion(mid):                right=mid            else:                left=mid        if isBadVersion(left):            return left        else:            return right

改进版本

class Solution(object): def firstBadVersion(self, n):     """     :type n: int     :rtype: int     """     left, right = 1, n     while left < right:         mid = (right + left) / 2         if isBadVersion(mid):             right = mid         else:             left = mid + 1     return left
0 0
原创粉丝点击