【easy】278. First Bad Version

时间:2023-03-08 18:30:30
【easy】278. First Bad Version

有一系列产品,从某个开始其后都不合格,给定一个判断是否合格的函数,找出N个产品中第一个不合格的产品。

正确答案:

// Forward declaration of isBadVersion API.
bool isBadVersion(int version); class Solution {
public:
int firstBadVersion(int n) {
int low = ;
int high = n;
int ver = ;
while (low < high) {
ver = low + (high - low) / ;
//这个题注意点!!如果直接high+low可能溢出,就会超时…… if (isBadVersion(ver)) {
high = ver;
} else {
low = ver + ;
}
}
return low;
}
};

=============

有一道非常类似的题目

猜数游戏:1-n之内有一个数是预选的数字,每次回告诉大还是小或者正确。返回猜中的数字。

// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num); class Solution {
public:
int guessNumber(int n) {
int start = ;
int end = n;
int res = ;
while (start<end){
int mid = start + (end-start)/;
if (guess(mid)==){
return mid;
}
if (guess(mid)==)
start = mid+;
else
end = mid-;
}
if (guess(start))
return start;
return end;
}
};