5月挑战Day1-First Bad Version

新的挑战开始了!!!

Day1-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.

就是给了一个数字,这个数字表示的意思是软件更新的最后一个版本号,但是这个软件之前有一个版本是坏的,而在那之后的版本都是坏的,为此需要我们找到第一个坏的版本,题中给了一个查询版本是否是坏的API,让我们尽量少的调用这个API解决这个问题,这道题光看下面官方给的例子就知道要用二分搜索吧,可能是新的挑战第一天要简单点,例子解析就是代码了我觉得。

Example:

Given n = 5, and version = 4 is the first bad version.

call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true

Then 4 is the first bad version. 
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):

class Solution:
    def firstBadVersion(self, n):
        """
        :type n: int
        :rtype: int
        """
        #二分搜索,例子都给出解法了吧。。
        start = 1
        end = n
        while start <= end:
            mid = (start + end) // 2
            if isBadVersion(mid):
                end = mid - 1
            else:
                start = mid + 1
        return start
        

时间复杂度为O(logn),在leetcode上这个解法的排名还是挺低的。我也好奇还有什么解法,所以去leetcode中的discuss中找到了下面这种解法,但是看不出来比二分搜索能高多少。。。

class Solution:
    def firstBadVersion(self, n):
        if isBadVersion(1): return 1
        b = [1,n]
        while 1:
            m, i, j = (b[0]+b[1])//2, b[0], b[1]
            b = [m,j] if isBadVersion(i) == isBadVersion(m) else [i,m]
            if j - i == 1: return j

这种解法本质上不也是用的二分搜索吗,只不过是用数组存储开始和结束数,为啥这道题的时间复杂度就比普通的二分搜索低呢。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值