278. First Bad Version

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

the real question is : given a sorted array, find the first appearance of certain number. the trick here is the return value, should it be left ? right? in this case always left. why ? if middle is not the number, so mid+1 becomes the left. if middle is the number, there are 2 scenarios, one this is the first number. one it is not:

  • in the first case, your left, mid and right eventually become the same, but the number is not the required, the next is, the binary search in this case will point left to next value(left = mid +1)
  • in the second case, your new right, mid -1 may be the desired number. so continue the search, you will eventually reach the first case.
/* 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 l = 1, r=n;
        while(l <= r){
            int m = l + (r-l)/2;
                r = m-1;
                l = m+1;

        return l;

results matching ""

    No results matching ""