- 输入:n = 5, bad = 4
- 输出:4
-
- 输入:n = 1, bad = 1
- 输出:1
- # 二分查找
- # 二分查找适用于单一目标,依次减少区间范围,判断返回即可。
- class Solution:
- def firstBadVersion(self, n: int) -> int:
- left, right = 1, n
- while left < right:
- mid = left + (right - left) // 2
- if isBadVersion(mid):
- right = mid
- else:
- left = mid + 1
- return left