First Bad Version

/**
 * 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.
*/




//oooooooxxxxxxxxx

//find the first position of X 
//which can use the template to 
//find the first position of target, 
//the taget is badverison in the problem
public class Solution {
    /*
     * @param n: An integer
     * @return: An integer which is the first bad version.
     */
    public int findFirstBadVersion(int n) {
        // write your code here
        
        if( n < 0){
            return -1;
        }
        
        int start = 1, end = n;
        
        while(start +1 < end){
            int mid = start + (end -start)/2;
            

            //to void call many time interface, just merge two condition together in else statement
            if(SVNRepo.isBadVersion(mid) == false){
                start = mid;
            }
            
            else{
                end = mid;
            }
        }
        
        if(SVNRepo.isBadVersion(start) == true){
            return start;
        }
        
        if(SVNRepo.isBadVersion(end) == true){
            return end;
        } 
        
        return -1;
    }
}

Last updated