方法一:(自己写的)
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
while(n>0){
if(isBadVersion(n)){
n--;
continue;
}
return n+1;
}
return 1;
}
}
会超时
方法二:
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int low=1,high=n;
while(low<high){
int mid=low+(high-low)/2;
if(isBadVersion(mid)){
high=mid;
}else{
low=mid+1;
}
}
return low;
}
}
如果mid是错误版本,则第一个错误版本在low到mid之间(含low和mid),所以令high=mid,如果mid是正确版本,则第一个错误版本在(mid+1)和high之间(含(mid+1)和high),所以令low=mid+1
不能照搬二分的代码,要灵活分析