Leetcode - First Bad Version

Question

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.

Java Code

public int firstBadVersion(int n) {
    if(n == 1) return 1;

    int i = 1, j = n;
    int pivot = (1 + n) / 2;//二分查找的中间位置

    //如果搜索区间内不少于2个版本,一直二分查找
    while(j - i > 1) {
        if(isBadVersion(pivot))//如果第pivot版是坏版本
            j = pivot;//则首个坏版本必不晚于此版本,即新搜索范围的上界
        else
            i = pivot + 1;//否则首个坏版本最早出现在下一个,即新搜索范围的下界

        pivot = (int)(((long)i + j)/2);//更新搜索区域的中轴位置,注意防止整型数据的溢出
    }

    //在剩余的两个版本中寻找最早的坏版本
    return isBadVersion(i) ? i : j;
}

更新

2016.05.08

  • 代码中防止整型溢出的语句也可以写成

    pivot = i + (j - i)/2;
    

    pivot = (i>>1) + (j>>1);
    

你可能感兴趣的:(LeetCode,二分查找,version,bad)