[LeetCode][JavaScript]First Bad Version

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而它前一个数不是,这个数就是结果,否则就进行二分。

 1 /**
 2  * Definition for isBadVersion()
 3  * 
 4  * @param {integer} version number
 5  * @return {boolean} whether the version is bad
 6  * isBadVersion = function(version) {
 7  *     ...
 8  * };
 9  */
10 /**
11  * @param {function} isBadVersion()
12  * @return {function}
13  */
14 var solution = function(isBadVersion) {
15     /**
16      * @param {integer} n Total versions
17      * @return {integer} The first bad version
18      */
19     return function(n) {
20         return findBadVersion(1, n);
21 
22         function findBadVersion(start, end){
23             var index = parseInt((start + end) / 2);
24             if(isBadVersion(index)){
25                 if(!isBadVersion(index - 1)){
26                     return index;
27                 }else{
28                     return findBadVersion(start, index - 1);
29                 }
30             }else{
31                 return findBadVersion(index + 1, end);
32             }
33         }
34     };
35 };

调用:

 1 function test(){
 2     var res = solution(
 3         function(version){
 4             if(version >= 5){
 5                 return true;
 6             }else{
 7                 return false;
 8             }
 9         }
10     )(15);
11     console.log(res);
12 };
原文地址:https://www.cnblogs.com/Liok3187/p/4803352.html