Sunday, November 15, 2015

Leetcode: First Bad Version

Difficulty: Easy
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.
Subscribe to see which companies asked this question
Hide Tags
 Binary Search
Show Similar Problems













----------------------------------
-----------------------------------
Binary search:
if mid is bad, right =mid-1;
if mid is good, left=mid+1;
see the following example for what's the return value:
So, the termination requirment is right>left, and the return value is alway r+1 (NOTE: if all versions are good, the r+1 will be n+1, not exist!). 
Also NOTE: using 
mid = l + (r - l) / 2;
instead of 
mid=(l+r)/2
to avoid l and r are too large to sum!!
///////////////////////////////////////
//CODE:
// Forward declaration of isBadVersion API.
 bool isBadVersion(int version);

 class Solution {
 public:
        int firstBadVersion(int n,vector<int> a) {
               //check input
               int l = 1, r = n, mid;
               while (l<=r){
                      mid = l + (r - l) / 2;
                      if (a[mid-1]){
                            r = mid - 1;
                            //mid=(l+r)/2;
                      }
                      else{
                            l = mid + 1;
                            //mid=(l+r)/2;
                      }

               }
               return r + 1;
        }
 };














No comments:

Post a Comment