leetcode278:First Bad Version

来源:互联网 发布:origin9.1绘图软件 编辑:程序博客网 时间:2024/05/21 19:35

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