有一系列产品,从某个开始其后都不合格,给定一个判断是否合格的函数,找出N个产品中第一个不合格的产品。
正确答案:
// Forward declaration of isBadVersion API. bool isBadVersion(int version); class Solution { public: int firstBadVersion(int n) { int low = 1; int high = n; int ver = 0; while (low < high) { ver = low + (high - low) / 2; //这个题注意点!!如果直接high+low可能溢出,就会超时…… if (isBadVersion(ver)) { high = ver; } else { low = ver + 1; } } 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 = 1; int end = n; int res = 1; while (start<end){ int mid = start + (end-start)/2; if (guess(mid)==0){ return mid; } if (guess(mid)==1) start = mid+1; else end = mid-1; } if (guess(start)) return start; return end; } };