原题网址:https://leetcode.com/problems/first-bad-version/
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.
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
long i=1, j=n;
while (i<=j) {
int m = (int)((i+j)/2);
if (isBadVersion(m)) j=m-1; else i=m+1;
}
return (int)i;
}
}

本博客介绍了一个利用二分法解决寻找第一个导致所有后续版本变坏的版本问题的方法,通过调用API `isBadVersion(version)` 来判断版本好坏,并最小化API调用次数。
215

被折叠的 条评论
为什么被折叠?



