1. Title
First Bad version
2. Address of the topic
https://leetcode.com/problems/first-bad-version/
3. Topic content
English:
You is 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 was developed based on the previous version and all of the versions after a bad version were 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 is bad.
Given an API bool Isbadversion (version) which would return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
Chinese:
Suppose you are a project manager of a leadership team developing new products, and now the latest version of the product has not passed the quality check, each version is based on the previous version of the development, if one version is a bad version, then the version behind this version is also a bad version. Assuming you now have n versions of your product (from 1 to N), you now need to find the location of the first bad version, which is the culprit behind the bad version of the later version.
The topic provides an API function Isbadversion with a Boolean return value that returns whether a version of the version number corresponds to a bad version. Write a function to find the first bad version, you need to minimize the number of times you call API functions.
4. Methods of Solving problems
Since the version number starts at 1 and continues to N, it is an ascending order, so you can use a binary lookup strategy to reduce the number of comparisons. It is important to note that when you take the median of a binary lookup, do not use left and right to add and then divide by 2, which may result in overflow at the time of calculation.
A section of Java code that implements this method is as follows:
/** * function Description:leetcode 278 - first bad version * Developer: Tsybius2014 * Development time: September 13, 2015 */public class solution extends versioncontrol { /** * find the first bad version * @param n Total versions * @return number of first bad version */ public int firstbadversion (int n) { if (n <= 0) { return 0; } if ( Isbadversion (1)) { return 1; } else if (!isbadversion (n)) { return Integer.MAX_VALUE; } int left = 1; int right = n; int mid; while (True) { mid = left + (right - left) / 2; //note left + right may have exceeded the maximum value of an integer if (Mid == left) { return right; } if (Isbadversion (mid)) { right = mid; } else { left = mid; } } }}
END
Leetcode:first Bad Version-the first one