LeetCode:First Bad Version - 第一个坏版本

1、题目名称

First Bad Version(第一个坏版本)

2、题目地址

https://leetcode.com/problems/first-bad-version/

3、题目内容

英文:

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个版本(从1到n),你现在需要找出第一个坏版本的位置,这个版本是导致后面版本都是坏版本的元凶。

题目中提供了一个返回值为布尔型的API函数isBadVersion,这个函数会返回某个版本号对应的版本是否是坏版本。写一个函数找出第一个坏版本,你需要将你调用API函数的次数降到最低。

4、解题方法

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

一段实现此方法的Java代码如下:

/**
 * 功能说明:LeetCode 278 - First Bad Version
 * 开发人员:Tsybius2014
 * 开发时间:2015年9月13日
 */
public class Solution extends VersionControl {
    
    /**
     * 找到第一个坏版本
     * @param n 总版本数
     * @return 第一个坏版本的序号
     */
    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; //注意 left + right 有可能超过了整数的最大值
            if (mid == left) {
                return right;
            }
            if (isBadVersion(mid)) {
                right = mid;
            } else {
                left = mid;
            }
        }
    }
}

END

转载于:https://my.oschina.net/Tsybius2014/blog/505462

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值