[Simple Algorithm] 32. The first wrong version

topic:

You are a product manager currently leading a team to develop a new product. Unfortunately, the latest version of your product did not pass QA. Since each version is developed based on the previous version, all versions after the wrong version are bad.

Suppose you have n versions [ 1 , 2 , ..., n] and you want to find out the first wrong version that caused all the errors below.

You can use the bool isBadVersion(version) interface to determine whether the version number version is wrong in unit tests. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Contributor:
Special thanks to @jianchao.li.fighter for adding this question and creating all the test cases.

 

Problem solving ideas:

This question is more interesting. On the surface, it must be calculated by binary search, but how to find the first wrong version is difficult. Use res to record every wrong version.

Similar to finding the first value in a sorted array that is less than this number but closest to this number. This topic is a key topic deformation topic, and usually requires more practice.

code show as below:

int binarySearch(vector<int> & nums,int target){
        int l = 0;
        int r = nums.size() - 1;
        int res = -1;
        
        while(l <= r){
            int mid = (l + r)/2;
            if(nums[mid] == target){
                return mid;
            }else if(nums[mid] > target){
                r = mid - 1;
            }else{
                res = mid;
                l = mid + 1;
            }
        }
        
        cout<<res<<endl;
        
        return res;
    }

 

 

Code:

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

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

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325276563&siteId=291194637