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>其餘就是二分法的基本算法了~不作詳細介紹~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章