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 returns whether version
is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
LeetCode Problem - 278: Link | Click Here
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
// Initialize low, high, and result variables
int low = 1;
int high = n;
int result = n;
// Perform binary search
while (low <= high) {
// Calculate mid point
int mid = low + (high - low) / 2;
// Check if the mid version is a bad version
if (isBadVersion(mid)) {
// Update the result to the current mid, and search in the left half
result = mid;
high = mid - 1;
} else {
// If the mid version is not bad, search in the right half
low = mid + 1;
}
}
// Return the result, which represents the first occurrence of a bad version
return result;
}
}