AC代码
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
if(n < 1) {
return -1;
}
int left = 1;
int right = n;
int ans = -1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(isBadVersion(mid)) {
ans = mid;
right = mid - 1;
}else {
left = mid + 1;
}
}
return ans;
}
}
精髓
跟上一篇类似,简化版本,仅仅去查找左边的端点,换个思路,其实也可以查找右边的端点,都是二分思想