其他分享
首页 > 其他分享> > 155-278. 第一个错误的版本

155-278. 第一个错误的版本

作者:互联网

假设你是程序员,你们n次git提交之前的都是对的,n+1次之后提交的代码都有问题,下在需要知道是从那次开始出现错误的,请设计算法isBadVersion函数可以判断这个版本是否是错误的(firstBadVersion1是我写的,难受啊越学越菜啊)
class Solution(object):
    def isBadVersion(self, n):
        if n < 2:
            return False
        return True

    def firstBadVersion1(self, n):
        """
        :type n: int
        :rtype: int
        """
        return self.mid_search(0, n) if n > 1 else n

    def mid_search(self, start, end):
        left = start
        right = end
        mid = (left + right) // 2

        flag = False
        while True:
            if self.isBadVersion(mid) is True and self.isBadVersion(mid - 1) is False:
                flag = True
                break

            if self.isBadVersion(mid) is False:
                left = mid + 1
                right = right

            if self.isBadVersion(mid) is True:
                left = left
                right = mid - 1
            mid = (left + right) // 2

        return mid if flag else -1

    def firstBadVersion(self, n):
        """
        :type n: int
        :rtype: int
        """
        left, right = 1, n
        while left < right:
            mid = left + (right - left) / 2
            if self.isBadVersion(mid):
                right = mid
            else:
                left = mid + 1
        return left


if __name__ == '__main__':
    s1 = Solution()
    nums = 4
    root = s1.firstBadVersion(nums)
    print(root)
    print("gfsdg")

标签:right,155,self,isBadVersion,mid,版本,278,True,left
来源: https://www.cnblogs.com/liuzhanghao/p/14328646.html