Saturday, April 23, 2016

LeetCode Q278: 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.

Solution:

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
long helper(long n, long left, long right){
if(left>right)
return -1;
int m = (left+right)/2;
bool b = isBadVersion(m);
if(!b)
return helper(n, m+1, right);
else{
if(m==1||!isBadVersion(m-1))
return m;
else
return helper(n, left, m-1);
}
}
int firstBadVersion(int n) {
long res=helper(n, 1, n);
return (int)res;
}
};
view raw Q278.cpp hosted with ❤ by GitHub


Round 2 solution:
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
long helper(long n, long l, long r){
int res;
if(l==r-1||l==r)
return isBadVersion(l+1)? l:r;
int m = (l+r)/2;
bool bad = isBadVersion(m+1);
if(bad)
res = helper(n, l, m);
else
res = helper(n, m, r);
return res;
}
int firstBadVersion(int n) {
long res=helper(n, 0, n-1);
return (int)res+1;
}
};
view raw Q278Rnd2.cpp hosted with ❤ by GitHub


Round 3 solution:
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int l = 1, r=n;
while(l<r-1){
int m = l+(r-l)/2;
bool tmp = isBadVersion(m);
if(tmp)
r=m;
else
l=m;
}
return isBadVersion(l)? l:r;
}
};
view raw Q278Rnd3.cpp hosted with ❤ by GitHub

No comments:

Post a Comment