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.


二分查找,查找的时候进入子区间前先检查一下避免错过查找位置。

因为这里查找的是第一个”坏的“位置,这个位置靠近左边,应该在进入左子区间前进行检查。


 public int firstBadVersion(int n)
	{
		return find(1, n);
	}
	
	
	public int find(int lo,int hi)
	{
		if(lo==hi)
			return lo;
		
		int mid=(int) (((long)lo+(long)hi)>>1);
		if(isBadVersion(mid))
		{
			if(mid-1>=lo&&isBadVersion(mid-1))
				return find(lo, mid-1);
			return mid;
		}
		
		return find(mid+1, hi);
	}



或者,换一种思路,从左边尽量地延伸。

https://discuss.leetcode.com/topic/26272/o-lgn-simple-java-solution/2


public int firstBadVersion(int n) {
    int start = 1, end = n;
    while (start < end) {
        int mid = start + (end-start) / 2;
        if (!isBadVersion(mid)) start = mid + 1;
        else end = mid;            
    }        
    return start;
}

---------------------------------------------------------------------------------------------


二分查找,若该元素出现多次,返回第一次出现的位置

public static int getPos(int[] A, int n, int val) {
		int lo=0,hi=n-1;
		int mid=lo;
		while(lo<hi){
			mid=lo+(hi-lo)/2;
			if(A[mid]<val){
				lo=mid+1;
			}else{
				hi=mid;
			}
		}
		return A[lo]==val?lo:-1;
	}


二分查找,若该元素出现多次,返回最后一次出现的位置


public static int getPos(int[] A, int n, int val) {
		int lo=0,hi=n-1;
		int mid=lo;
		while(lo<hi){
			mid=lo+(hi-lo+1)/2;
			if(A[mid]>val){
				hi=mid-1;
			}else{
				lo=mid;
			}
		}
		return A[hi]==val?hi:-1;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值