[LeetCode#278]First Bad Version

Problem:

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.

Analysis:

This problem is simple, you just need to maintain a right invariant, and use the idea of binary search to chop off uncessary part! But there is a very important caution in using binary search. 

Basic idea: (use the idea from binary search to chop off uncessary part!)
Step 1: compute the mid index through front index and end index. 
Step 2: update on the front and end idex to chop off uncessary part.
2.1 iff mid is bad version, it means the first bad version must no greater than mid, we could chop all elements after mid index.
if (isBadVersion(mid)) {
    end = mid;
}
Note: the mid may be the first bad version, we should keep it.

2.2 iff mid is good version, it means the first bad version must appear at appear mid index, we could chop all elements before mid index. (inclusive)
if (!isBadVersion(mid)) {
    front = mid + 1;
}

Wrong solution:

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int front = 1;
        int end = n;
        while (front < end) {
            int mid = (front + end) / 2;
            if (isBadVersion(mid)) {
                end = mid;
            } else {
                front = mid + 1;
            }
        }
        return front;
    }
}

Mistakes Analysis:

Last executed input:
2126753390 versions, 1702766719 is the first bad version.

The problem for the above solution is the way of calculating mid, which could cause overflow problem.
int mid = (front + end) / 2;
We should use following safety way.
int mid = left + (right - left) / 2;

What's more.
What if there is no bad version? we should directly return -1.
if (!isBadVersion(n)){
    return -1;
}

Solution:

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        if (!isBadVersion(n)){
            return -1;
        }
        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;
    }
}
posted @ 2015-09-08 12:24  airforce  阅读(502)  评论(0编辑  收藏  举报