题目
https://leetcode.com/problems/first-bad-version/
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.
代码
21 / 21 test cases passed
Runtime: 0 ms
这道题主要需要注意的是n可能很大,low+high
和mid+1
都可能超过int,所以用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; // 有可能超过int,所以用long
bool bad = isBadVersion(mid);
if (bad) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return high + 1;
}
附: 一些输入
Last executed input:2147483647 versions
2147483647 is the first bad version.
Last executed input:2126753390 versions
1702766719 is the first bad version.