First Bad Version

本文介绍了一种使用二分查找算法来高效确定首次出现故障的产品版本的方法,并针对大数值运算可能出现的溢出问题提供了两种解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

思路:

这道题很明显用二分查找,使用二分查找后。但输入n = 2126753390,firstBadVersion = 1702766719后,一直超时,后面用Eclipse调试的时候发现,是大数相加溢出造成的。改用long后accept

P.S.注意溢出

 1 /* The isBadVersion API is defined in the parent class VersionControl.
 2       boolean isBadVersion(int version); */
 3 
 4 public class Solution extends VersionControl {
 5     public int firstBadVersion(int n) {
 6         long low = 1;
 7         long high = n;
 8         long middle = 0;
 9         while(low <= high){
10             middle = (low + high) / 2;
11             if(isBadVersion((int)middle)){
12                 if(middle == 1 || !isBadVersion((int)middle - 1))
13                     return (int)middle;
14                 else
15                     high = middle - 1;
16             }//if
17             else
18                 low = middle + 1;
19         }//while
20         
21         return -1;
22     }
23 }

 在讨论区看到有解决溢出问题的,没有用long。我觉得很漂亮

1 middle = low + (high - low) / 2;

P.S.但这尼玛跑的速度居然比用long更长

转载于:https://www.cnblogs.com/luckygxf/p/4923489.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值