力扣-10.15-278

本文探讨了两种改进的`firstBadVersion`算法,针对`isBadVersion`接口,一种采用迭代方式避免超时,另一种利用二分查找策略灵活调整搜索范围。理解这两种策略对于解决Version Control问题至关重要。
摘要由CSDN通过智能技术生成

在这里插入图片描述
方法一:(自己写的)

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

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        while(n>0){
            if(isBadVersion(n)){
                n--;
                continue;
            }
            return n+1;
        }
        return 1;
    }
}

会超时

方法二:

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

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int low=1,high=n;
        while(low<high){
            int mid=low+(high-low)/2;
            if(isBadVersion(mid)){
                high=mid;
            }else{
                low=mid+1;
            }
        }
        return low;
    }
}

如果mid是错误版本,则第一个错误版本在low到mid之间(含low和mid),所以令high=mid,如果mid是正确版本,则第一个错误版本在(mid+1)和high之间(含(mid+1)和high),所以令low=mid+1

不能照搬二分的代码,要灵活分析

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值