[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
nversions
[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
versionis 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); };
相关文章推荐
- JavaScript : the good parts(语言精髓读书笔记)
- js实现找零张数最小问题
- JSP页面细节
- JavaScript所有保留字
- javascript高级程序设计---CSS操作
- js中substr,substring,indexOf,lastIndexOf等的用法
- 转载:JavaScript中对闭包的理解及举例和说明
- jsessionId的使用
- URL与资源(之Url地址栏中的jsessionId有分号)《包括相对路径和绝对路径的根本分析》
- 自己封装的AJAX (带JSON)
- javascript高级程序设计---Element对象
- 7个最好的javascript资源
- 纯js代码实现未知宽高的元素在指定元素中垂直水平居中显示
- Andorid中使用Gson和Fast-json解析库解析JSON数据---第三方库学习笔记(二)
- 20150912 javascript事件-获取样式
- javascript 判断一个点是否在多边形内(向量的使用)
- 【转】获取/设置IFRAME内对象元素的几种JS方法
- javascript高级程序设计---document节点
- javaScript学习(一)
- jsp 行动标签