Describtion
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
解题思路:
使用binary search的方法进行处理
该题目应该是属于简单题,直接上代码
/**
* 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) {
// write your code here
if (n == 0) {
return 0;
}
int start = 1;
int end = n;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (SVNRepo.isBadVersion(mid)) {
end = mid;
} else {
start = mid;
}
}
if (SVNRepo.isBadVersion(start)) {
return start;
}
if (SVNRepo.isBadVersion(end)) {
return end;
}
return -1;
}
}