278. First Bad Version
Given n = 5, and version = 4 is the first bad version.
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version. // Forward declaration of isBadVersion API.
bool isBadVersion(int version);
int firstBadVersion(int n) { // time: O(logn); space: O(1)
int start = 1, end = n;
while (start < end) {
int mid = start + (end - start) / 2;
if (!isBadVersion(mid)) start = mid + 1;
else end = mid;
}
return start;
}Last updated