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.
Solution:
Use Binary search, get middle element, if bad version, search first half. otherwise search last half part.
public int firstBadVersion(int n) {
long begin = 1;
long end = n;
if(n<1) return 0;
while(begin<end){
long mid = (begin+end)/2;
if(isBadVersion((int)mid)){
end = mid-1;
}else{
begin = mid+1;
}
}
if(isBadVersion((int)begin)) return (int)begin;
return (int)begin+1;
}

本文介绍了一种使用二分查找法来找出首个导致后续版本均为不良产品的版本的方法,通过调用API判断每个版本的状态,最小化API调用次数。

被折叠的 条评论
为什么被折叠?



