首页 技术 正文
技术 2022年11月19日
0 收藏 746 点赞 2,947 浏览 1095 个字

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 -; }
};
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,078
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,553
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,402
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,177
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,814
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898