278. 第一个错误的版本
https://leetcode-cn.com/problems/first-bad-version/
解法一:二分
题目简化为一个布尔值序列:[f, f, f, ..., t, t, t],求第一个t出现的位置,即f和t的右分界。 用二分法,初始left=1,right=n,先求中点mid,易推知当V(mid)==false,说明mid在f区间,要找中点应向右扩展:left=mid+1。反之向左扩展
class Solution:
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
left = 1
right = n
while left <= right:
mid = left + (right - left) // 2
if isBadVersion(mid): #题目提供函数
right = mid - 1
else:
left = mid + 1
return left
最后更新于