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.

这道题比较简单,可是我却也琢磨了很久,其实看到这道题第一个反应就是二分查找。专业点说,这是一个寻找左边界的问题。

思路就是:如果头部是bad version的话,可以返回;如果mid是坏的话,坏的源头必然在head和mid之间,那么尾部就可以变为mid了。如果mid不是坏的,那么坏的必然在mid和尾部之间,所以头部会变成mid。(就是二分查找了!)

但是刚开始mid=(head+tail)/2会time exceed(因为直接加head+tail有可能会溢出)。说明【自己没有良好的代码习惯】,以前看书的时候就说,二分查找,最好写成mid=low+(high-low)/2。因为time exceed,又考虑了别的思路,导致这道题做了很久。

// Forward declaration of isBadVersion API.
bool isBadVersion(int version); class Solution {
public:
int firstBadVersion(int n) {
if(n==) return -;
int head=,tail=n,mid=;
while(head<=tail){
mid=head+(tail-head)/;
if(isBadVersion(head)) return head;
if(isBadVersion(mid)) {head++; tail=mid;}
else head=mid+;
}
return -; }
};

最新文章

  1. 微软发布正式版SQL Server 2016
  2. CSS导航菜单水平居中的多种方法
  3. C# Random生成多个不重复的随机数万能接口
  4. [Android]Volley源码分析(三)
  5. [原创]Net实现Excel导入导出到数据库(附源码)
  6. ASP.NET MVC3升级到ASP.NET MVC4 的方法
  7. MDAC 在WINDOWS XP SP3 不能安装 的解决方法
  8. Oracle 经常使用命令小结
  9. Android入门之简单短信发送器
  10. 【CentOS如何最小化安装】
  11. Server对象
  12. 【知识整理】这可能是最好的RxJava 2.x 入门教程(二)
  13. tensorflow实现RNN及Word2Vec
  14. JavaScript系统对象
  15. for循环的实例
  16. bat删除过期文件(FORFILES)
  17. sublime的lua插件
  18. Docker之Swarm
  19. BinaryReader 自己写序列化
  20. ubuntu 12.04下编译安装nginx-1.9.3

热门文章

  1. 浅入深出之Java集合框架(上)
  2. WriteTeacherObj
  3. 简单的使用Seajs
  4. voa 2015 / 4 / 14
  5. Unreal Engine 4 Radiant UI 插件入门教程(二)
  6. JavaScript 的 作用域
  7. 新浪微博的OAuth2认证过程
  8. git bash上传代码到github
  9. nyoj_16:矩形嵌套
  10. Selenium自动化初级/中级网络授课班招生