[LeetCode/LintCode] First Bad Version

Problem

The code base version is an integer start from 1 to n. One day, someone committed a bad version in the code case, so it caused this version and the following versions are all failed in the unit tests. Find the first bad version.this

You can call isBadVersion to help you determine which version is the first bad one. The details interface can be found in the code's annotation part.code

Notice

Please read the annotation in code area to get the correct way to call isBadVersion in different language. For example, Java is SVNRepo.isBadVersion(v)get

Example

Given n = 5:it

isBadVersion(3) -> false
isBadVersion(5) -> true
isBadVersion(4) -> true
Here we are 100% sure that the 4th version is the first bad version.io

Challenge

You should call isBadVersion as few as possible.class

Solution

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int start = 1, end = n;
        while (start <= end) {
            int mid = start+(end-start)/2; 
            //分析最後一次循環的時刻:
            //當start與end相差小於2時,mid老是start, 那麼若是start是bad,下一次直接跳出循環,返回start
            //當start與end相差大於2時,mid是bad,end變成mid-1,若是mid是first bad,循環結束的條件將是:
            //end stays on the same position, start = end+1 --> start goes to the first bad position
            //循環結束,返回start
            if (isBadVersion(mid)) {
                end = mid-1;
            } else {
                start = mid+1;
            }
        }
        return start;
    }
}

Update 2018-9

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

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        if (n == 0) return 0;
        int i = 1, j = n;
        while (i < j) {
            int mid = i+(j-i)/2;
            //mid could be the first bad, so DON'T do: j = mid-1
            if (isBadVersion(mid)) j = mid;
            //when mid is not bad, just DO: i = mid+1 
            else i = mid+1;
        }
        return j;
    }
}
相關文章
相關標籤/搜索