leetcode278:First Bad Version

1、原题如下:
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.

2、解题如下:

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        int left =1;
        int right = n;
        int test;
        while (left<right)
        {
            test = left+(right-left)/2;//1
            if(isBadVersion(test))
                right=test;
            else 
                left = test+1;//2
        }
        return left;
    }
};

3、解析
此题难度不大,主要的注意点为注释中的两点~如果稍不留意,也是做不出来的~
1>注释1,采用代码test = left+(right-left)/2;而非test=(left+right)/2;是因为int类型,测试例子给的数值会很大,导致某些例子的结果超出2的31次方(或者63次方,根据电脑的位数而有所不同)从而出现错误。所以,尽量用题中所写的方式表示中值,笔者在这里卡了很久。。。好不容易才想明白为什么这样通不过测试。
2>注释2,其实这里加不加1并不影响算法的实现,但是不加1需要多调用isBadVersion函数一定的次数(请自行理解why~),不信大家可以试试,而这样就有可能会导致isBadVersion函数调用太多导致时间超标无法通过测试,毕竟题目要求You should minimize the number of calls to the API.–笔者在这里细化了好久才将这个二分法调用的次数尽可能地压缩了下来~
3>其余就是二分法的基本算法了~不作详细介绍~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值