LeetCode278:First Bad Version

Requirements:
You are a product manager, he is leading a team to develop new products. Unfortunately, the latest version of the product that you did not pass quality inspection. Since each version is developed on the basis of a previous version, all versions after a bad version is also bad.
Suppose you have n versions [1, 2, ... you want to find the first bad, it causes all the bad below.
Do you have a API bool isBadVersion (version), it will return version is bad. Implement a function to find the first bad version. You should minimize calls to the API.
Test:
# 1: to true to true to true to false to true
output:. 4
# 2: to false to true
output: 2
#. 3: to false to false
Output: 1

代码:
/ The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version);
/

public class Solution extends VersionControl {
public int firstBadVersion(int n) {

    int left = 1;
    int right = n;

    while (left < right)
    {
        int mid = left + (right - left) / 2;

        if(isBadVersion(mid))
        {
            right = mid;
        }
        else
        {
            left = mid + 1;
        }
    }

    return right;

}

}

Guess you like

Origin blog.51cto.com/14016747/2457007