Leetcode 278. First Bad Version

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

1. Description

First Bad Version

2. Solution

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

1
2
3
4
5
6
7
8
9
10
11
12
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/
如果有收获,可以请我喝杯咖啡!