Iterative java solution


  • 0
    O
    
        public int firstBadVersion(int n) {
            if (n == 1) {
                return 1;
            }
            boolean isBad = false;
            int mid = (int)Math.ceil(n/2), low = 1;
            while(n - mid > 1) {
                isBad = isBadVersion(mid);
                if (isBad) {
                    n   = mid;
                    mid = (int)Math.ceil(n/2);
                } else {
                    low = mid;
                    mid = low + (n-low)/2;
                }
            }
            
            return isBadVersion(mid) ? mid : n;
        }
    

Log in to reply
 

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