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.
题意:有[1,n]个连续数,其中大于等于某个数的值都是不符合要求的,让你调用最少次数的 isBadVersion(version) 方法去找出那个数。类似于有一栋n层高的楼,某一层开始扔东西下去就会摔坏,找出那一层。
解题思路:二分查找
代码:
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;