First Bad Version
Http://lintcode.com/en/problem/first-bad-version
The code base version is a integer and start from 1 to N. One day, someone commits a bad version of the code case, so it caused itself and the following versions is all failed in t He unit tests.
You can determine whether a version was bad by the following interface:
 
java:
public VersionControl {
    }
c++:
class VersionControl {
public:
bool isbadversion (int version);
};
python:
class VersionControl:
Find the first bad version.
Note
You should call Isbadversion as few as possible.
Please read the annotation in code area to get the correct-on-the-isbadversion in different language. For example, Java is versioncontrol.isbadversion.
Example
Given n=5
Call Isbadversion (3), Get false
Call Isbadversion (5), Get True
Call Isbadversion (4), Get True
Return 4 is the first bad version
Challenge
Don't call isbadversion exceed O (Logn) times.
Tags ExpandSolution 1:Nine Chapters algorithm template solution, note, must use Left + 1 < Right as the condition of while, this will not produce a dead loop and cross-border situation.
1 /**2 * public class VersionControl {3 * public static Boolean isbadversion (int k);4 * }5 * can use Versioncontrol.isbadversion (k) to judge wether6 * The KTH code version is bad or not.7 */8 classSolution {9 /**Ten * @paramn:an integers. One * @return: An integer which are the first bad version. A */ - Public intFindfirstbadversion (intN) { - //Write your code here the if(n = = 1) { - return1; - } - + intleft = 1; - intright =N; + A while(Left + 1 <Right ) { at intMid = left + (right-left)/2; - if(Versioncontrol.isbadversion (mid)) { -right =mid; -}Else { -left =mid; - } in } - to if(Versioncontrol.isbadversion (left)) { + returnLeft ; - } the * returnRight ; $ }Panax Notoginseng}
View CodeSolution 2:
You can also simplify a little bit:
1 /**2 * public class VersionControl {3 * public static Boolean isbadversion (int k);4 * }5 * can use Versioncontrol.isbadversion (k) to judge wether6 * The KTH code version is bad or not.7 */8 classSolution {9 /**Ten * @paramn:an integers. One * @return: An integer which are the first bad version. A */ - Public intFindfirstbadversion (intN) { - //Write your code here the if(n = = 1) { - return1; - } - + intleft = 1; - intright =N; + A while(Left <Right ) { at intMid = left + (right-left)/2; - if(Versioncontrol.isbadversion (mid)) { -right =mid; -}Else { -left = mid + 1; - } in } - to returnRight ; + } -}
View Code
Lintcode:first Bad Version Problem solving report