问题描述:
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.
说明:一个叫做isBadVersion(version) 的API给我们用,它可以用来检测一个版本是否可行。我们要找到一系列版本中第一个不好的版本(自从第一个不好的版本出现后,后面都不好了,之前都没事),比如:TTTTTFFFFFFFFFF, 表示从第6个版本开始出现的质量问题
思路:
二叉搜索,没啥说的
注意二叉搜索的几个问题:
- 搜索左侧区间时,设right=mid
- 搜索右侧区间时,设left=mid+1
- 求中点区间时用left+(right-left)/2可以避免整型越界
代码如下:
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int left=1;
int right=n;
while(left<right){
//int mid=(left+right)/2;
int mid = left + (right - left) / 2;
if(isBadVersion(mid)==true){
right=mid;
}
else{
left=mid+1;
}
}
return left;
}
}
时间复杂度: O(logn)