A simple Java solution using binary search


  • 0
    L
    public int firstBadVersion(int n) {
            if(n<=0) {
                return -1;
            }
            //1,2
            int s = 1;
            int e = n;
            while(e>=s) {
             int p = (e-s)/2 + s;
             if(isBadVersion(p)) {
                 if(p==1 || !isBadVersion(p-1)) {
                     return p;
                 }
                 else {
                    //go left.
                    e = p-1;
                 }
             }
             else {
                 //go right.
                 s = p+1;
             }
            }
            return -1;
            
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.