【LeetCode】278. First Bad Version 解题记录
问题描述
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, …, n] and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
测试样例
1 | Input: n = 5, bad = 4 |
1 | Input: n = 1, bad = 1 |
说明
1 | 1 <= bad <= n <= 2^31 - 1 |
解题
思路
使用二分法即可
补充:
-
时间复杂度
O(logn)
-
注意计算中值时,最好使用
int mid = l + (r - l) / 2
,若使用mid = (l + r) / 2
,当数字非常大时,Integer 溢出,会导致错误!!!
代码
1 | /* The isBadVersion API is defined in the parent class VersionControl. |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 哆啦 C 梦!
评论