这道题是二分法查找第一个符合条件的元素
需要注意两个边界条件
1 start = mid + 1 : 如果用start = mid,只剩两个相邻的元素时候可能会卡死 2 mid = start + (end - start)/2 : 如果用(end + start)/2, end + start可能会超过整数最大值
/* 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 start = 1;
int end = n;
int mid = start + (end - start)/2;
//(low+high)有超出int上限的可能性
while(start < end){
mid = start + (end - start)/2;
if(isBadVersion(mid)){
end = mid;
}else{
start = mid + 1;
}
}
return end;
}
}