278. First Bad Version

通过二分查找策略,高效定位导致后续版本皆错的第一个故障版本,大幅减少API调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.


题意:

你是一个产品经理,当前正领导着一个团队开发一个新产品。不幸的是,这个新产品最近的版本在质量检查的的失败了。每个版本都是基于前一个版本的基础上开发的,一个失败的版本之后的所有版本都是坏的。有n个版本号,想找到第一个失败的版本,它导致了后面所有的版本错误。给定bool isBadVersion(version)函数,该函数返回该版本是否是失败的版本。实现一个功能去找到第一个失败的版本,并且尽可能少的调用提供的API。


思路:

由于版本号是从1开始,一直到n,属于增序排列,因此可以采用二分查找的策略,减少比较次数。需要注意的是,在取二分查找的中间值时,不要使用左右相加后再除以2的方式,这样可能会在计算时产生溢出

代码:20ms

/* 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;
        
        if (isBadVersion(1)) {
            return 1;
        } else if (!isBadVersion(n)) {
            return Integer.MAX_VALUE;
        }
        
        int left = 1;
        int right = n;
        
        int mid;
        while (true) {
            mid = left + (right - left) / 2;
            if (mid == left) {
                return right;
            }
            if (isBadVersion(mid)) {
                right = mid;
            } else {
                left = mid;
            }
        }
    }
}
另一版本:C++版:0ms

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);


class Solution {
public:
    int firstBadVersion(int n) {
        int left = 1, right = n;
        while (left < right) {
            int mid = left + (right - left)/2;
            if (isBadVersion(mid))
                right = mid;
            else
                left = mid + 1;
        }
        return left;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值