您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]First Bad Version

2015-09-12 18:08 591 查看

First Bad Version

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.

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

找出第一个bad version,bad version之后的version都是bad,version的范围是正整数,isBadVersion是已经写好的方法,只要调用就行了。

二分法,如果一个数是bad version而它前一个数不是,这个数就是结果,否则就进行二分。

/**
* Definition for isBadVersion()
*
* @param {integer} version number
* @return {boolean} whether the version is bad
* isBadVersion = function(version) {
*     ...
* };
*/
/**
* @param {function} isBadVersion()
* @return {function}
*/
var solution = function(isBadVersion) {
/**
* @param {integer} n Total versions
* @return {integer} The first bad version
*/
return function(n) {
return findBadVersion(1, n);

function findBadVersion(start, end){
var index = parseInt((start + end) / 2);
if(isBadVersion(index)){
if(!isBadVersion(index - 1)){
return index;
}else{
return findBadVersion(start, index - 1);
}
}else{
return findBadVersion(index + 1, end);
}
}
};
};


调用:

function test(){
var res = solution(
function(version){
if(version >= 5){
return true;
}else{
return false;
}
}
)(15);
console.log(res);
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: