Leetcode 278. First Bad Version

2021-03-02 16:28:31 浏览数 (1)

文章作者:Tyan 博客:noahsnail.com | CSDN | 简书

1. Description

2. Solution

解析:问题变为给定有序数组[1, 2, 2],找出第一个2的问题,最容易想到的就是二分查找。

代码语言:javascript复制
class Solution:
    def firstBadVersion(self, n):
        left = 1
        right = n
        while left <= right:
            mid = (left   right) // 2
            if isBadVersion(mid):
                if mid == 1 or not isBadVersion(mid - 1):
                    return mid
                right = mid - 1
            else:
                left = mid   1

Reference

  1. https://leetcode.com/problems/first-bad-version/

0 人点赞