LintCode First Bad Version

时间:2022-01-26 23:55:32

找出第一个出问题的version。

/**
* public class SVNRepo {
* public static boolean isBadVersion(int k);
* }
* you can use SVNRepo.isBadVersion(k) to judge whether
* the kth code version is bad or not.
*/
class Solution {
/**
* @param n: An integers.
* @return: An integer which is the first bad version.
*/
public int findFirstBadVersion(int n) {
if(n <= 0) return -1; int left = 1; int right = n;
while(left + 1 < right){
int mid = (left + right) / 2;
if(SVNRepo.isBadVersion(mid) == true){
right = mid;
}
else{
left = mid;
}
}
if(SVNRepo.isBadVersion(left)){
return left;
}
else if(SVNRepo.isBadVersion(right)){
return right;
}
else return -1;
}
}