LeetCode 278 First Bad Version (First Bad Version) (bipartite )(*)
Translation
You are a product manager and are currently leading the team to develop a new product. Unfortunately, the previous version of the product did not pass the quality check. Because each version is developed based on the previous version, versions after the bad version are also bad. Suppose you have n versions [1, 2,..., n], and you want to find the first bad version that causes all later versions to deteriorate. Give you an API -- bool isBadVersion (version), which can determine whether a version is bad. Implement a function to find the first bad version. You should call this API as little as possible.
Original
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.
Analysis
As a matter of fact, we have mentioned so many questions. To solve this problem, we only need to use the bipartite method, but it is very error-prone in the middle.
// Forward declaration of isBadVersion API.bool isBadVersion(int version);class Solution {public: int firstBadVersion(int n) { int l = 0, r = n; while (l < r) { int mid = l + (r - l) / 2; if (isBadVersion(mid)) r = mid; else l = mid + 1; } return l; }};
I wrote the sixth question today, so tired ......