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 will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
考察 二分法查找。
public int firstBadVersion(int n) {
int start = 1;
int end = n;
while(start <= end)
{
int mid = start+(end-start)/2;
boolean isBad = isBadVersion(mid);
if( isBad )
{
if(mid == 1)
{
return mid;
}else if( mid >1 && !isBadVersion(mid-1))
{
return mid;
}else if(mid >1 && isBadVersion(mid-1))
{
end = mid -1;
}
}else
{
start = mid +1;
}
}
return -1;
}
一开始自己写完答案总不对,对比别人的代码和自己有一处不同,int mid = start+(end-start)/2 而我写的是 int mid = (start+end)/2. 如果 就单比较结果 发现,这2者其实没什么区别啊?但是 为什么就不对呢。但其实画图一想
(start+end)/2 求的是2数的平均数,而start+(end-start)/2 求的是 start 和 end 中间的那个数,也正是我们题所要求的。但其实 2个运算表达式是没有区别的。
后来查了资料 原来是 (start+end)/2容易存在溢出问题,超过了int的范围。
而 start+(end-start)/2 不存在溢出问题。最大的可能情况也是 int的最大范围值。
写程序得考虑周全额。下面是一个讨论帖子
http://bbs.youkuaiyun.com/topics/391838265?page=1