First Bad Version

Question (LC.278)

At some point in the version control system, a bug was introduced. Find where this bug occurred (first bad version).

Example

Input: [T, T, T, T, F, F]
Return: 4

Analysis

First position of target. Read the question carefully since you need make an API call.

Code

public int firstBadVersion(int n) {
    int start = 1, mid, end = n;
    while (start + 1 < end) {
        mid = start + (end - start) / 2;
        if (isBadVersion(mid)) {
            end = mid;
        } else {
            // the code still works, search into the future (the right section)
            start = mid + 1;
        }
    }
    // base case start and end next to each other
    if (isBadVersion(start)) {
        return start;
    } else if (isBadVersion(end)) {
        return end;
    } else {
        return -1; // no bad version
    }
}

results matching ""

    No results matching ""