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.


题意:

现在有n个版本的产品,已知从某个版本产品坏了之后,后面的版本产品都是坏的。写一个函数,找出第一个产品坏掉的版本。已知有个接口函数isBadVersion(n)可以用来判断第n个版本产品是好的还是坏的,要求尽量少地调用接口函数isBadVersion(n).


代码:

# 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
        """
    
        if isBadVersion(1) == True :                  #先判断第一个版本是不是坏的
            return 1
        else :                   #如果第一个版本是好的,开始二分查找第一个坏的版本
            low = 1                   #low:标记好的产品的版本
            high = n                 #high:标记坏的产品的版本
            
            while low < high :
                temp = (low+high)/2                #找中点
                if isBadVersion(temp) == True :            #如果中点是坏的版本,则将high移到中点
                    high = temp
                if isBadVersion(temp) == False :         #如果中点是好的版本,则将low移到中点
                    low = temp
                if low + 1 == high :                       #如果好、坏版本挨着了,则退出循环
                    break
            return high                       #返回第一个坏的版本

笔记:

与普通的二分查找中high = temp-1,low = temp+1 有点不同,具体问题要具体分析



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值