[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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值