278. First Bad Version [easy] (Python)

来源:互联网 发布:linux内核优化 编辑:程序博客网 时间:2024/05/16 10:37

题目链接

https://leetcode.com/problems/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.

题目翻译

大概意思就是:假设你有n个版本号 [1, 2, …, n], 其中从某个版本号开始往后的所有版本都是错误版本,你想找到第一个错误的版本号。
你可以调用一个预实现的接口 bool isBadVersion(version),它会返回输入的版本号 version 是否是错误版本号。你需要实现一个找到第一个错误版本号的函数,尽量少的调用该接口。

思路方法

思路一

暴力顺序搜索会超时,符合题意要采用二分搜索法。这里稍微需要注意的是,你要找的元素应该符合这样的特征:或者它是第一个版本号,或者它是错误版本号且它前一个版本号是正确版本号。

代码

# 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        """        left, right = 1, n        while True:            mid = (left + right) / 2            if isBadVersion(mid):                if mid == 1 or not isBadVersion(mid - 1):                    return mid                right = mid - 1            else:                left = mid + 1

思路二

类似上面的思路,其实可以不对错误的版本号进行特殊的判断操作,而是在缩小搜索范围时仍将当前错误版本号包含在新的区间内,那么最终区间只有一个元素时即为所求。

代码

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

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/52048093

0 0