leetcode 278. First Bad Version
2016-04-03 21:47
323 查看
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
You are given an API
bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
这题按理说是很简单的,二分查找嘛。单提交答案却出现wrong answer,还是负的,不可能啊。试了几次都出现这样的情况,百思不得其解。想了好久,突然想到一处可能出现错误,high+low可能出现溢出,操,改了之后就通过了。
bool isBadVersion(int version);
int firstBadVersion(int n) {
if (isBadVersion(1))
return 1;
long long int low = 1,high = n;
while (high > low)
{
if (isBadVersion(high))
{
long long int r=(high + low) / 2;
high = r;
}
else
{
long long int r=2 * high - low;
if(r>n)
high=n;
else
high=r;
r= (low + high) / 2;;
low =r;
}
}
return high+1;
}
accepted
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.
这题按理说是很简单的,二分查找嘛。单提交答案却出现wrong answer,还是负的,不可能啊。试了几次都出现这样的情况,百思不得其解。想了好久,突然想到一处可能出现错误,high+low可能出现溢出,操,改了之后就通过了。
bool isBadVersion(int version);
int firstBadVersion(int n) {
if (isBadVersion(1))
return 1;
long long int low = 1,high = n;
while (high > low)
{
if (isBadVersion(high))
{
long long int r=(high + low) / 2;
high = r;
}
else
{
long long int r=2 * high - low;
if(r>n)
high=n;
else
high=r;
r= (low + high) / 2;;
low =r;
}
}
return high+1;
}
accepted
相关文章推荐
- tomcat如何开启GZIP
- UVA 10537(最短路)
- JAVA大数类 BigInteger和BigDecimal用法
- 20145221 《Java程序设计》第五周学习总结
- [html][LigerUI]使用示例
- 20159320《网络攻防实践》第5周视频总结
- 二叉树
- About Traffic Manager Monitoring
- Azure Resource Manager overview
- 随笔
- 第三周项目四(6)-猜数字
- cmake 学习笔记(三)
- Java重写方法与初始化的隐患(转)
- 构建之法阅读笔记02
- 课体回顾,杂质半导体
- 开始我的代码生涯
- IOS_绘画交集圆填充
- python shlex
- Spring(四)注解配置Ioc
- urlib2下载器网页的三种方法