Leetcode 278. First Bad Version

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

1. Description

First Bad Version

2. Solution

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

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/

你可能感兴趣的:(Leetcode 278. First Bad Version)