First Bad Version

Posted codingEskimo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了First Bad Version相关的知识,希望对你有一定的参考价值。

O(logN)

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

 

以上是关于First Bad Version的主要内容,如果未能解决你的问题,请参考以下文章

278. First Bad Version

LC.278. First Bad Version

leetcode 278 第一个错误的版本 (First Bad Version)

278. First Bad Version

278. First Bad Version

278. First Bad Version