[LeetCode] First Bad Version 第一個壞版本


 

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

 

話說這個叫李建超的哥們太贊了,自從LeetCode開始收費后,大多數的免費題都是這哥們出的,還寫了所有的test cases,32個贊。這道題說是有一系列版本,其中有一個版本是壞的,而且后面跟着的全是壞的,給了一個API函數可以用來判定當前版本是否是壞的,讓我們盡可能少的調用這個API,找出第一個壞版本。那么這種搜索題最先開始考慮用二分查找法把,效率高嘛。由於這題很有規律,好版本和壞版本一定有個邊界,那么我們用二分法來找這個邊界,對mid值調用API函數,如果是壞版本,說明邊界在左邊,則把mid賦值給right,如果是好版本,則說明邊界在右邊,則把mid+1賦給left,最后返回left即可。需要注意的是,OJ里有個坑,那就是如果left和right都特別大的話,那么left+right可能會溢出,我們的處理方法就是變成left + (right - left) / 2,很好的避免的溢出問題,參見代碼如下:

 

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

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

 

如果習慣了二分搜索法從0開始找,可以用下面的方法:

 

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

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

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM