278. The first wrong version
You are a product manager, he is currently leading a team to develop new products. Unfortunately, the latest version of your product did not pass quality inspection. Since the previous version of the development of each version is based, so all later versions of the wrong version is wrong.
Suppose you have n versions [1, 2, ..., n], you want to find out first of all lead to the wrong version after version error.
You can call bool isBadVersion (version) interfaces to determine whether the version number version error in unit tests. Implement a function to find the first incorrect version. You should try to reduce the number of API calls.
Example:
Given n = 5, and a first version = 4 is the wrong version.
Call isBadVersion (3) -> false
calls isBadVersion (5) -> true
calling isBadVersion (4) -> true
So 4 is the first wrong version.
/* 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 lo = 1, hi = n;
while(lo <= hi){
int mid = lo + (hi - lo) / 2;
if(isBadVersion(mid)){
hi = mid - 1;
}else{
lo = mid + 1;
}
}
return lo;
}
}