问题描述

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.

查找第一个坏版本问题。比如说有一系列版本号:[1,2,3,4,5],假设第3个版是Bad Version,那么它之后的版本[4,5]也是Bad Version,所以对应的是否是bad Versiond的数组为:[0,0,1,1,1],而版本3处于好版本与坏版本的相交点。现在的问题就是找这个相交点。

思路

使用折半查找法不断逼近交界点。

代码

Java代码(含测试):

public class Solution {
	
	public static void main(String[] args) {
		System.out.println("start...");
		makeTest(2126753390, 1702766719);
		makeTest(2,2);
		makeTest(100,2);
		makeTest(3,3);
		makeTest(4,4);
		makeTest(2,1);
		makeTest(100,1);
		makeTest(99,1);
		System.out.println("finished.");
	}
	
	public Solution(int firstBad) {
		this.firstBad = firstBad;
	}
	
	private int firstBad;
	
	public int firstBadVersion(int n) {
        int l = 1;
        int r = n;
        int m = l+(r-l+1)/2;
        while(l<r-1) {
        	if(isBadVersion(m)) {
                r = m;
            } else {
                l=m;
            }
            m=l+(r-l+1)/2;
        }
        if(isBadVersion(l)) return l;
        if(isBadVersion(r)) return r;
        return n;
    }
	
	private boolean isBadVersion(int n) {
		return n>=this.firstBad;
	}
	
	public static void makeTest(int n, int firstBad) {
		Solution s = new Solution(firstBad);
		Assert.assertEquals(firstBad, s.firstBadVersion(n));
	}
	
}