LeetCode -- First Bad Version

Quesion:

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.

Analysis:

题目大意是:假设你是一个生产商经理,当前正领导生产一批新的产品。但是不幸的是,你的最近一个版本的产品被检查出质量问题。因为每个版本的生产都会依赖前一个版本,因此一旦某个版本出现问题,它后面的所有版本都将出现问题。

假设你已经有n个版本[1,2,3,……,n],现在需要找出里面出错的第一个版本。你可以使用API isBadVersion(version)来检测某个版本是否有问题,但是要求尽可能的少使用这个API。

分析:这相当与一个二分查找的问题,每次从中间一个版本查起,若当前版本没问题,说明问题版本出现在后面一半中;若当前版本出现问题,说明第一个问题版本出现在前面一半中。一定要注意结束条件以及返回的数值。

Answer:

    public int firstBadVersion(int n) {
        if(n == 0)
                return 0;
        if(isBadVersion(1)) //若第一个版本有问题,则后面所有都有问题
                return 1;
        
        if(!isBadVersion(n)) //若最后一个版本都没有问题,说明所有都没有问题
            return Integer.MAX_VALUE;
        
        int left = 1, right = n;
        while(true) {
                int mid = left + (right - left) / 2; //注意直接用(left + right) 可能会超过Integer的最大的范围
                if(left == mid)
                    return right;
                else {
                    if(isBadVersion(mid) == true) {
                        right = mid;
                    } else {
                        left = mid;
                    }
                }
        }
    }
原文地址:https://www.cnblogs.com/little-YTMM/p/4813435.html