一、题目名称java
First Bad Version(第一个坏版本)函数
二、题目地址code
https://leetcode.com/problems/first-bad-version/leetcode
三、题目内容开发
英文:get
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.it
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.io
中文:function
假设你是一个领导团队开发新产品的项目经理,如今产品的最新版本没有经过质量检查,每一个版本都是基于上一个版本开发的,若是有一个版本是坏版本,那么该版本后面的版本也是坏版本。假设如今你的产品有n个版本(从1到n),你如今须要找出第一个坏版本的位置,这个版本是致使后面版本都是坏版本的元凶。
题目中提供了一个返回值为布尔型的API函数isBadVersion,这个函数会返回某个版本号对应的版本是不是坏版本。写一个函数找出第一个坏版本,你须要将你调用API函数的次数降到最低。
四、解题方法
因为版本号是从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