Leetcode_278_First Bad Version

97 篇文章 0 订阅
94 篇文章 18 订阅

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/49719255



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.


思路:

(1)题意为给定一系列版本号,要求找出第一个出错的版本号。(其中,当前的版本是基于前一个版本的,一旦某个版本出错,则当前版本后续的版本都会出错)

(2)该题主要考察二分查找。可以把1,2,...n一系列版本表示为 good,good,......,good,bad, bad,.....,只需通过二分查找算法进行判断,需要注意的是:如果发现当前版本是好的,则需要将start指向mid的下一个位置。

(3)详情见下方代码。希望本文对你有所帮助。

package leetcode;

public class First_Bad_Version {
	
	// 找出第一个坏的
    public int firstBadVersion(int n) {
        
    	int start = 0;
    	int end = n;
    	
    	while(start <=end) {
    		int mid = start +(end -start) >> 1;
    	
    	    // 是坏的,则从当前往后找
    		if(isBadVersion(mid)){
    			end = mid;
    			
    			
    		}else {
    			start = mid + 1;
    			
    		}
    	}
    	
    	return end;
    	
    }
    
    static boolean isBadVersion(int version){
    	return true;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值