LintCode : 第一个错误的代码版本

LintCode : 第一个错误的代码版本

代码库的版本号是从 1 到 n 的整数。某一天,有人提交了错误版本的代码,因此造成自身及之后版本的代码在单元测试中均出错。请找出第一个错误的版本号。

你可以通过 isBadVersion 的接口来判断版本号 version 是否在单元测试中出错,具体接口详情和调用方法请见代码的注释部分。

二分查找。


/** * class VersionControl { * public: * static bool isBadVersion(int k); * } * you can use VersionControl::isBadVersion(k) to judge whether * the kth code version is bad or not. */
class Solution {
public:
    /** * @param n: An integers. * @return: An integer which is the first bad version. */
    int findFirstBadVersion(int n) {
        // write your code here
        int low, high, mid;
        low = 1;
        high = n;
        while(low < high){
            mid = (low + high) / 2;
            if (VersionControl::isBadVersion(mid)) high = mid - 1;
            else if (!VersionControl::isBadVersion(mid)) low = mid + 1;
        }
        if (VersionControl::isBadVersion(low)) return low;
        else return low + 1;
    }
};



你可能感兴趣的:(二分查找,lintcode)