Topics
https://leetcode.com/problems/first-bad-version/
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 T O 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. Code
21/21 Test Cases passed
runtime:0 ms
The main need to note is that N may be large, low+high and mid+1 may be more than int, so use long.
Forward Declaration of isbadversion API.
BOOL Isbadversion (int version);
int firstbadversion (int n) {
if (n = = 1) {
return 1;
}
Long low = 1;
Long high = n;
Long mid = 0;
while (low <= high) {
mid = (low + high)/2;//may exceed int, so use long
bool bad = Isbadversion (mid);
if (bad) {High
= mid-1,
} else {Low
= mid + 1;
}
}
return high + 1;
}
attached: some inputs
Last executed input:2147483647 versions 2147483647 was the first bad
version.
Last executed input:2126753390 versions 1702766719 was the first bad
version.