题目链接 278.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.
Example:
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.
题意
一个位置出错了,其后面的所有位置均会出错,要求以最少的次数求出第一个出错的位置。
思路1
- API
isBadVersion(version)
返回当前版本是否是bad
- 二分出分界点即可
- 注意初始时的范围是
1 - n
- 取中点时为了避免溢出使用
int mid = (r - l) / 2 + l;
代码1
// The API isBadVersion is defined for you.
// bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int l = 0, r = n;
while(l < r)
{
int mid = (r - l) / 2 + l; // 防止溢出
if(isBadVersion(mid))
r = mid;
else
l = mid + 1;
}
return l; // 一定有错误,一定有解,无需额外判断
}
};