74. First Bad Version


做题历程:

  1. 本题在Leetcode中肯定是做过的,本次耗时8分钟独立解出

本题就是套模板即可,跟前面几道Binary Search基本没有区别。

直接上代码了:

/**
 * class SVNRepo {
 *     public:
 *     static bool isBadVersion(int k);
 * }
 * you can use SVNRepo::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 start = 1;
        int end = n;
        while (start + 1 < end) {
            int middle = start + (end - start) / 2;
            if (SVNRepo::isBadVersion(middle)) {
                end = middle;
            }
            else {
                start = middle + 1;
            }
        }
        if (SVNRepo::isBadVersion(start)) {
            return start;
        }
        return end;
    }
};

results matching ""

    No results matching ""