LintCode 74. First Bad Version 原创Java参考解答

LintCode 74. First Bad Version 原创Java参考解答

问题描述

http://www.lintcode.com/en/problem/first-bad-version/

The code base version is an integer start from 1 to n. One day, someone committed a bad version in the code case, so it caused this version and the following versions are all failed in the unit tests. Find the first bad version.

You can call isBadVersion to help you determine which version is the first bad one. The details interface can be found in the code’s annotation part.

Notice

Please read the annotation in code area to get the correct way to call isBadVersion in different language. For example, Java is SVNRepo.isBadVersion(v)

Example

Given n = 5:

isBadVersion(3) -> false
isBadVersion(5) -> true
isBadVersion(4) -> true

Here we are 100% sure that the 4th version is the first bad version.

解题思路

这道题讲需要在SVN版本控制下查找第一次出错的那个版本。

看题的本质是在是一组数列数据[1, 2, 3, …. n]中找到符合犯错条件的第一个位置。在数据中找位置的题目正是Binary Search二分法所能解决的。

因为是要找第一次出错的位置,因此当二分的mid位置为错时候,把end 设置为mid,再继续对保留下来的二分前半部分进行二分。二分循环过后,只剩下首尾两数,如果首数位置SVN版本检查为错,则为首数。反之则为尾数。

参考代码

/** 
 * 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) { 
        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; 
        } else { 
            return end; 
        } 
    } 
} 

相关题目

LintCode All in One 原创题目讲解汇总

发表回复

您的电子邮箱地址不会被公开。