Question
Solution
题目大意:产品有5个版本1,2,3,4,5其中下一个版本依赖上一个版本,即版本4是坏的,5也就是坏的,现在要求哪个版本是第一个坏的。
思路:二分法,middle-1好,middle坏,middle就是第一个坏的版本
Java实现:
/* 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 left = 1, right = n;
int badVersion = -1;
while (badVersion == -1) {
int middle = left + (right-left)/2;
boolean pre = isBadVersion(middle-1);
boolean cur = isBadVersion(middle);
if (!pre && cur) {
badVersion = middle;
} else {
// false true middle is BadVersion
// false false left = middle + 1;
// true false x
// true true right = middle - 1;
if (pre) {
right = middle-1;
} else {
left = middle + 1;
}
}
}
return badVersion;
}
}
参考:
public int firstBadVersion(int n) {
int start = 1, end = n;
while (start < end) {
int mid = start + (end-start) / 2;
if (!isBadVersion(mid)) start = mid + 1;
else end = mid;
}
return start;
}